Entity Framework 5, Multiple Models, Same Entity - entity-framework

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.

Related

Entity Framework Code First unique constraint across multiple tables

So I'm creating a database model using Entity Framework's Code First paradigm and I'm trying to create two tables (Players and Teams) that must share a uniqueness constraint regarding their primary key.
For example, I have 3 Players with Ids "1", "2" and "3" and when I try to create a Team with Id "2", the system should validate uniqueness and fail because there already exists a Player with Id "2".
Is this possible with data annotations? Both these entities share a common Interface called IParticipant if that helps!
Txs in advance lads!
The scenario you are describing here isn't really ideal. This isn't really a restriction on Entity Framework; it's more a restriction on the database stack. By default, the Id primary key is an Identity column, and SQL itself isn't really supportive of the idea of "shared" Identity columns. You can disable Identity and manage the Id properties yourself, but then Entity Framework cannot automatically build navigation properties for your entities.
The best option here is to use one single participant table, in a technique called "Table Per Hierarchy", or TPH. Entity Framework can manage the single table using an internal discriminator column. Shared properties can be put into the base class, and non-shared properties can be put on the individual classes, which Entity Framework will composite into a single large table in the DB. The main drawback to this strategy is that columns for non-shared properties will automatically be nullable in the database. This article describes this scenario very well.
The more I try to come up with a solution, I realize that this is an example of the XY Problem. There is not really a good solution to this question, because this question is already a proposed solution. There is a problem here that has led you to create an Interface which you suggest requires the entities which are using the interface to have a unique Id. This really sounds like an issue with the design of the Interface itself, as Interfaces should be agnostic to the entity they are applied to. Perhaps providing some code and showing what your problem actually is would be helpful, since the proposed solution you are asking how to implement here isn't really practical.

Should Entities in Domain Driven Design and Entity Framework be the same?

I have started using Entity Framework Code First for the first time and am impressed by the way in which our greenfield application is being built around the domain rather than around the relational database tables (which is how I have worked for years).
So, we are building entities in C# that are being reflected in the database every time we do a new migration.
My question is this: should these same entities (i.e. designed with Entity Framework in mind) play the same role as entities in Domain Driven Design (i.e. representing the core of the domain)?
Object-Relational Mapping and Domain-Driven Design are two orthogonal concerns.
ORM
An ORM is just here to bridge the gap between the relational data model residing in your database and an object model, any object model.
An Entity as defined by EF concretely means any object that you wish to map some subpart of your relational model to (and from). It turns out that the EF creators wanted to give a business connotation to those by naming them Entities, but in the end nothing forces you that way. You could map to View Models for all it cares.
DDD
From a DDD perspective, there's no such thing as "an Entity designed with EF in mind". A DDD Entity should be persistence ignorant and bear no trace of any ORM. The domain layer has no interest in how, where, whether or when its objects are stored.
Where the two meet
The only point where the two orthogonal concepts intersect is when the object model targeted by your ORM mapping is precisely your domain model. This is possible with what EF calls "Code first" (but should really be named regular ORM), by pointing to your DDD Entities in separate EF mapping files living in a non-domain layer, and refraining from using EF artifacts such as data annotations directly in your Entity classes. This is not possible when using Database First, because the DDD "purity" part of the deal wouldn't be met.
In short, the terms collide, but they should really be conceptually considered as two different things. One is the domain object itself and the other is a pointer that can indicate the same bunch of code, but it could point to pretty much anything else.
They shouldn't be the same as they're designed for different purposes. An ORM entity is a facade for 1 or more tables, its purpose is to simulate OOP on top of relational tables. A Domain Entity is about defining a Domain concept. If your Domain Entity turns out to be just a data structure, then you can reuse it as an EF entity, but that's just one case.
A DDD app never knows about EF or ORM. It only knows about a Repository. Hence, your Domain Objects (DO) don't know either about EF. You can choose to consider them EF entities, as an implementation detail, BUT... you should do that ONLY after your DOs are defined and their use cases implemented. You should defer as much as possible the implementation of persistence (use in-memory repos (lists) for devel).
When you reach that point you'll know if you can reuse your DO for ORM purposes or if you'll need other ways (such as a memento).
Note that a design of a DO while driven by the Domain, it should take into consideration the persistence issue, but it shouldn't be influenced by it i.e don't design your DO according to the db schema. The persistence strategy can be different for each DO and it might involve or not an ORM.
If you're using Event Sourcing for a DO, ORM doesn't exist. Same for serialized objects. It matters a lot how an object will be used by the app (updating and querying), that's why I've said you should defer the persistence implementation. For a lot of DOs you won't need a rdbms (even if you're using it) so an ORM entity will look more like a KeyValuePair (Id => serialized data).
In conclusion, they are different things for different purposes, that might look identical for some cases (CRUD scenarios).
I would say, they can be the same.
Sometimes there is no need to support two models. When you follow code first approach, your entities model your domain, your infrastructure (ORM) separates domain and persistence layers.
It might be reasonable to maintain two models if you have legacy database and have to maintain it.
There are two other SO questions that can be helpful:
Repository pattern and mapping between domain models and Entity Framework
Advice on mapping of entities to domain objects
Well.That's The Approach i use.And I've seen a lot of others doing the same.Now am using The Onion Architecture/Pattern to Create my application and making Everything rely on the domain entities made my life easier.because whenever i want to change for example the Layer that deal with my database ,i can do that without changing the UI layer(ASP.NET MVC app,WPF app...etc)...I suggest doing the same.
let's wait for other posts
I agree with what MikeSW said (3rd Answer).When you design your domain entities,you should do that without caring about who will consume those entities (ORMs or any other technology serving whatever purpose).design them with one idea in mind : they will be reusable and they will not need to be changed in the future (hopefully)

What is included in DbContext model?

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.

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...

How to model Aggregates using Entity Framework?

While I have been dealing with domain-driven design (DDD) for quite some time now, I'm relatively new to Entity Framework (EF), and one question that came to my mind when using the Entity Framework Designer in Visual Studio was how Aggregates should be represented/modeled in EF.
Following DDD best practices, Entities should only reference other Entities (or Value Objects) within the same Aggregate, and references to other Entities are restricted to Root Entities of Aggregates (Aggregate Roots). However, I don't see any of these concepts present in EF (i.e., all Entities are treated alike, and consequently no restrictions are applied on references between Entities).
Thus, I'm asking: did I miss something in EF, or is it completely agnostic about Aggregates, Aggregate Roots and references between Entities? If the latter is the case, how do you model Aggregates when using Entity Framework?
I think DDD is other level of abstraction so my answer is no EF by default does not follow these practicies. It is up to you to model your entities and repositories to follow DDD. You will use repositories to build your aggregate root with loaded related entities related only to current aggregate root and you will use domain services to work with different repositories.
I just wanted to correct a small (but pretty important detail):
You state that "Entities should only reference other Entities (or Value Objects) within the same Aggregate".
Of course, there could be some arguments for this, but it's stricter than what at least one resource on DDD recomends: "Objects inside an Aggregate should be allowed to hold
references to roots of other Aggregates." ("Domain-Driven Design Quickly" by Avram & Marinescu).
Best regards,
Simon