What is included in DbContext model? - entity-framework

Description:
I've tried to separate certain domain segments into different DbContexts.
Each has several DbSets, but there are some DbSets that are shared, for example the UserProfile.
The reason for this separation is the speed at which the model is generated and the simplicity (less sets in an object, helps with intellisense).
However, I am not sure about what exactly belongs to the model that is generated.
Q1: Is every entity that is transitionally connected with the entities, for which a DbSet exists in a DbContext, included in the model?
Q2: If so, would that mean that performance-wise it serves no purpose to separate the domain into different contexts, since everything that is connected ends up in the model anyway, no matter which DbSets are stated in the DbContext?
Where can I find more information on how the model is generated? I've read a book on EntityFramework and CodeFirst and couldn't find that specific information...

Answering your first question: yes, all relations are modeled including the entities on both sides, so every entity that's connected by a navigation property to an included entity will also be included in the model regardless if there's a DbSet for it or not.
Entity Framework doesn't force you to create DbSets for all entities. This can be handy if you want to "restrict" child entities to only be accessible through their parents.
Regarding your second question: separating your contexts might still improve performance, if not all entities belonging to one context are reachable via navigation properties of entities belonging to the other context. There could be an additional cost associated with explicitly including more DbSets in a context, too.
You could read (some parts of) the Entity Framework source code, it's open-source and available on CodePlex to learn more about how the model is built.

Related

Entity Framework 5, Multiple Models, Same Entity

Ok, so I am new to entity framework...
I have an existing SQL database with some 500 tables in it, and we are in the process of considering a move from Linq->SQL to Entity Framework as our main data access layer. We also want to consider more of a domain driven design approach with separate data contexts managing key areas of the application ( i.e. Sales, Marketing, Jobs, Shipping etc. etc. ).
If we take a common entity such as "Customer", this appears in more than one model. I have two models in my sample app so far. Entity Framework is clever enough to create only one customer class ( we are using the default Poco T4 templates for class generation ), however when I try and run the project I get the following error "Multiple types with the name 'Customer' exist in the EdmItemCollection in different namespaces. Convention based mapping requires unique names without regard to namespace in the EdmItemCollection".
So am I right in thinking that Entity Framework does not allow "Customer" to exist in more than one model ? If I really want customer appearing in more than one model, do I have to start creating different versions of the customer class to deal with it ?
Apologies in advance if this is a dumb question, but I am relatively new to EF.
Thanks...
You said that you are creating DDD with bounded context. In bounded context, you create more than one context with one or more related entities in it. Why do you want to create more than one model with the same name?
Check the Julie Lerman's link for reference:
http://msdn.microsoft.com/en-us/magazine/jj883952.aspx
Sorry if I am out of context. But, in my experience in such a scenario, we have to create two different context such as "MarketingModelContext" and SalesModelContext. MarketingModelContext will have all the dbsets related to marketingmodel along with customer entity. In the same way, SalesModelContext will have all the dbsets related to SalesModel along with customer entity. In this way, you will be creating only one customer entity or POCO which can be used by two contexts independently. This is known as bounded contexts as Julie Lerman calls it. It will help you in separation of context, concerns and helps you with better performance as only required context(fewer entities) can be loaded. The above article will help you with this.
Hope I have answered your query.

What's an entity in entity framework?

In the tutorials im following for learning about the entity framework, they keep mentioning entities. I often see it gets used as a synonym for the dbsets<> in the database context class, but what's the literal meaning of it?
I already know how the entity framework works, I just dont understand the meaning of the word.
In Entity Framework an entity is largely equivalent to a class in the conceptual model (or the class model, which is mapped to the store model).
In domain model terms an entity is
An object that is not defined by its attributes, but rather by a thread of continuity and its identity.
(Source: Wikipedia)
That quite a mouthful for "an object with an identity", as opposed to a value object, like a DateTime or (maybe) an Address. A Customer is an entity, because it is identified by "who" he is. Two customers with the same name are still two customers.
So entities can loosely be defined as the "things" the business domain is about. The things both the customer/user and the system designer/developer talk about in ubiquitous language. And in EF those things are represented by classes.
So it's not the DbSet. The DbSet is a repository that provides entity objects.
I often see people referring to entities as models. I don't know the origin of this terminology (it seems to happen too often to be a coincidence), but I don't think it's correct. It's mostly confusing. The model in EF is either the store model or the conceptual model, so it's a collection of entities. A model can also be a view model that comprises any number of attributes of any number of entities.
Lets take a Person object for example and lets say the Person data is being posted to a database and its moving through the tiers
When its in my UI, I call it a Person Model or ViewModel.
When its in my business layer I call it a Person Business Object.
When its in my Data Layer, I call it a Person Entity.
Its the same data that is moving into different objects in different tiers. The entity is just the name of the object that is holding the Person data in the Data Access tier....
An entity is simply an object that represents some form of relational data. This is typically used for representing relational databases, but it is not confined to that. I suggest looking at http://msdn.microsoft.com/en-us/data/aa937709 for a brief overview of how the Entity Framework works.

Many domain models sharing one data context in EF 5

I recently, out of ignorance and lack of time, merged the domain models (POCO entity classes) from several projects into one 'DataModel' project, because I didn't want to duplicate dedicated DbContexts over all the projects. It struck me as ideal that something generic might be done, like a DbContext extension, to which one can add DbSet instances from various client projects.
I have read mention of such things, normally in the same circles as authors that contend - and I agree wholeheartedly - that the repository functionality is fulfilled completey by the DbSet class.
Can anyone offer any advice for building a generic DbContext which can exist in one project, where other projects can all have their domain models (sets of domain entities) registered with the shared DbContext, where they are all allocated they own DbSet to act as their repository?
building a generic DbContext which can exist in one project, where other projects can all have their domain models (sets of domain entities) registered
Interesting idea, but I'm not sure what you would gain by that.
For one, you'd never be able to simply type db.Customer (or similar). It should always be genericdb.Set<Customer>(), not knowing whether genericdb knows about Customer at all. (It may not have been registered).
Then, how should this registering take place? There are two ways to let a context map a class to a database model:
Creating a DbSet property in a DbContext-derived class and rely on code-first default conventions concerning table and column names, pluralization, etc.
Providing mapping configuration.
The first option defeats the purpose of a generic context class, so you'd have to register the domain classes by supplying EntityTypeConfiguration<T>s for each class in the domain, also for classes that normally could do without. (This should be done in the context's constructor, by the way.)
A further implication would be that somewhere you'd need a component/service that knows which groups of classes belong together and is able to deliver a coherent list of configurations. So, in stead of having dedicated contexts as an organizing principle out of the box you'd have to create your own organizer.
But back to the start. Couldn't you create a DAL that contains a DbContext factory that supplies the contexts as they previously existed for your projects? You don't have to duplicate dedicated DbContext classes this way.

Using my own domain model objects with .edmx in Entity Framework

I have a domain model architecture in which my domain/business objects were created based on the problem domain and independent of any knowledge of the physical data model or persistence structures. So far I'm on track because it's perfectly acceptable and often the case that there is an impedance mismatch between the domain model and the data model. A DBA created the database for getting the data they required, but it does not encapsulate the applications entire domain model or design.
The result - I have my own set of domain model objects. However all of the fields that need to be persisted do exist somewhere or another within my domain model, but not necessarily in the shape that my auto generated .edmx POCO entities have them. So I have all the data, it's just not in the perfect shape exactly like the tables in which auto generated POCO entities are created from.
I have seen a few posts on this topic like converting POCO entity to business entity and Entity Framework 4 with Existing Domain Model that make statements like the following:
"Create the entities in your entity data model with the same names as
your domain classes. The entity properties should also have the same
names and types as in the domain classes"
What!? No way, why should I have to make my domain model be reshaped to POCOs that are modeled exactly after the data model / table structure in the database? For example - in my case of having 5 given properties, 2 might be in class 'A' and 3 in class 'B', whereas a auto generated POCO class has all 5 in its own class 'A'.
This is the entire point, I want separation of my object model and data model but yet still use an ORM like EF 5.0 to map in between them. I do not want to have to create and shape classes and properties named as such in the data model.
Right now my .edmx in EF 5.0 is generating the POCO classes for me, but my question is how to dissolve these and rewire everything to my domain objects that contain all this data but just in a different shape?
By the way any solution proposed using a Code First approach is not an option so please do not offer this. I need some guidance or a tutorial (best) using EF5 (if possible because EF4 examples are always inheriting POCOs from ObjectContext) with wiring up my own business objects to the .edmx.
Any help or guidance is appreciated, thanks!
This sounds like exactly the use case of Entity Framework. I am making a few assumptions here. First that when you make this statement:
"I have a domain model architecture in which my domain/business objects were created based on the problem domain and independent of any knowledge of the physical data model or persistence structures."
That you mean this domain was created in the EF designer? But then you say:
"However all of the fields that need to be persisted do exist somewhere or another within my domain model, but not necessarily in the shape that my auto generated .edmx POCO entities have them."
This sounds to me like my first assumption is incorrect.
Next, you dismiss code first? If your domain model/business objects are code based and you want to persist them to a relational database, that is exactly the use case for code first. You have the code, now you need to create your DbContext and map it to your physical model.
However you dismiss that... so some thoughts:
If you have a domain model of code based business objects and you have an EDMX that is used for other things I think you would want to create a repository layer that uses something like auto mapper or manual projections to query your Entities and return your business objects.
If you have a domain model of code based business objects and you have an EDMX that is not used for other things other than persisting your business objects I would say that you need to express your domain in an EDMX and then map it onto your existing database. This is really the use case for an ORM. Having two domain models and mapping from one model to the other where one model matches your domain and one matches your database is adding an extra un-needed layer of plumbing.
The latter approach above is what is called "Model First" in EF parlance. There are several articles written about it although the bulk of them just generate the db from the model. You would not do that step, rather you would map your entities onto your existing database.
The basic steps for this are to "update from the database" not selecting any of the db objects (or entities would be created). Or, you can take your exiting .edmx in the designer (which is sounds like you have) and modify the entities to match your business domain. Or just delete all the entities in your EDMX model, create your entities as you want them, and then map them all.
Here is a jing I made where I use the EF Designer to bring in the model store (the only way to do this is to allow it to generate entities) and then delete the entities allowing the Store information to stay by clicking NO when it asks if you want to delete the table info.
http://screencast.com/t/8eiPg2kcp
I didn't add the POCO generator to this, but if I did it would generate the Entities in the designer as POCO classes.
The statement quoted above is not suggesting that you rewrite your domain objects to match your pocos, it is suggesting that you update the edmx to match your domain model.
In your example you could create an entity in your edmx that maps all 5 properties from both tables and EF will manage the mapping to and from the single generated Poco onto your tables.
Of course this means that you then have duplicate domain objects and pocos, meaning you would either have to manually convert your domain objects to pocos when interacting with EF,
or you could define your domain data objects as interfaces and provide partial implementations of the pocos that essentially identify each poco as being a concrete implementation of a domain object.
There are probably several other ways to skin this particular cat, but I don't think that you can provide predefined c# objects for use in an edmx.
One approach might be to select into a ViewModel (suited to your particular business logic) and automatically map some data from the context into it like so https://stackoverflow.com/a/8588843/201648. This uses AutoMapper to map entity properties from an EF context into a ViewModel. This won't do everything for you, but it might make life a bit easier. If you're unhappy with the way this occurs automatically, you can configure AutoMapper to do things a bit differently (see Projection) - https://github.com/AutoMapper/AutoMapper/wiki/Projection
You might know this already, but its also possible to automatically generate POCOs from your EDMX using t4 - http://visualstudiogallery.msdn.microsoft.com/72a60b14-1581-4b9b-89f2-846072eff19d. If you define the templates to generate partial classes, you can then have another partial class with your custom properties for that POCO. That way you can have most properties automatically populated, but have other custom properties which you populate with custom rules from your context/repository. This takes a lot of the monotony out of generating these, and you can then focus on reshaping the data using the above technique.
If you're seriously unhappy with both, you could always map a stored procedure to get the exact field names that you want automatically without needing to stuff around. This will of course affect how you work with the data, but I have done it before for optimisation purposes/where a procedure already existed that did exactly what I wanted. See http://msdn.microsoft.com/en-us/data/gg699321.aspx

Entity Framework & Class Models in MVC

I'm new to the MVC way of developing applications and for the most part am enjoying. One thing I'm a bit confused about is the use of the Entity Framework. The EF usually (at least in my experience) defines multiple tables and relationships through the .edmx table. A couple of questions:
Why would I define a separate class file for a specific table if EF is building all of the classes that I need in the background?
From some of the validation approaches that I've seen, they want to define validation logic in the class related to a model for a table. If I'm using EF, will I have a .cs file describing the model and a .edmx describing that same table (in addition to its associated tables)?
If yes, how do you connect the .cs file to the .edmx definition so that CRUD flows easily from the EF?
Sorry if these seem like easy questions but I'm just trying to get my head wrapped around these fundamental concepts. Too many examples out there use only a single table where in my business, I NEVER write an application that uses a single table. There are always multiple tables in relation to each other with foreign keys. Thanks for your prompt responses.
For a tutorial that shows the use of partial classes -- in a Web Forms application but for MVC the same technique would be used -- see Adding Metadata to the Data Model in this tutorial:
http://www.asp.net/web-forms/tutorials/getting-started-with-ef/the-entity-framework-and-aspnet-getting-started-part-8
From your comment "The EF usually (at least in my experience) defines multiple tables and relationships through the .edmx table." it sounds like you are familiar only with Database First and Model First -- for an introduction to Code First and an explanation of the differences, followed by a series of tutorials with an MVC example using Code First, see this tutorial:
http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application
Good questions, Darryl. Here are my responses to your bullet points:
Defining separate model classes that match the data models that EF creates is generally a good idea for the simple sake of separating your data access "stuff" from your business model objects that will get used throughout your app. Some people don't like this approach because it creates some amount of overhead when it comes to mapping your entities to POCOs but, if you use a tool such as AutoMapper, the overhead is minimal. The benefit lies in you creating a layer of separation between you and your (likely) evolving data model.
You could define validation logic in a buddy class (just a partial class that sits along-side your entity) but that would mean that you would be using that entity across your app and some would debate that that isn't the best idea. The alternative method, as mentioned above, is to create your own POCOs to mirror the entities that EF creates and place your validation attributes on the POCOs.
I mentioned this in the previous item but the way to do this would be to define buddy classes. Give EF buddy classes a Google and you should find plenty of examples on how to do that.
Just to add to all of this, if you choose to create POCO classes that mirror your EF entities, tools like AutoMapper can handle fairly complex relationships when it comes to mapping classes. So, if you have foreign key relationships in your data model, AutoMapper can understand that and map your POCO classes accordingly (i.e.: You have an entity that has a 1-to-many relationship and a POCO with a list of objects to mirror that relationship.)
I hope some of that helps...