Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to support Multiple Entity Framework Models in the same solution

I have begun developing an application using the Entity Framework.

I have added a namespace to contain all of my user management code MyApp.Users for example, and this contains a model that has been marked internal to the namespace and only exposes functionality to the rest of the system via interfaces. This is all good.

I now wish to define another namespace to handle specific business logic. I want it to contain a model that only knows about another subset of the database schema, however this subset overlaps on the Users table. When I try to access the second model in the main project, I get this error:

"An EdmType cannot be mapped to CLR classes multiple times"

I feel that this should not behave in this way. After all the user table is being referenced by 2 different models in 2 different namespaces... how does VS even know that the table is being referenced twice?

Has anybody seen this problem and perhaps figured out how to allow the same table to exist in different models?

Alternatively - Does this represent some kind of Entity Framework Anti-Pattern that I should be avoiding?

like image 912
RobD Avatar asked Oct 05 '09 11:10

RobD


2 Answers

In order to reuse types in multiple models, you need to follow some specific steps outlined in this blog post. Like many more advanced Entity Framework features, this works, but doesn't work so well with the GUI designer. See also this intro post for more ideas on dealing with larger models.

like image 138
Craig Stuntz Avatar answered Jan 03 '23 16:01

Craig Stuntz


You can definitely have multiple models - but they cannot overlap. The error message is pretty clear - if they do overlap, how would EF know which CLR type to map to - there's no way of telling that, really.

In your case, you could possibly try to extract the Users table into a third model of its own, if it needs to be used in two other places as well.

Marc

like image 23
marc_s Avatar answered Jan 03 '23 18:01

marc_s