Inheritance of Entity Framework in different collections

I'm new to the Entity Framework, but the more I worked with it, the more I liked it. But now my passion is in jeopardy as I struggle with a problem that has already made me crush my head against the wall.

The problem is this:

I am using Entity Framework 5.0 with a code approach and inheritance for my business models represented by a table in a hierarchy. At first, I had all the types of entities that were supposed to be displayed in the same assembly as my DbContext (which worked fine for both TPH and TPT). But since they also contain logic that depends on other assemblies, this turned out to be a good approach, because it caused circular dependencies, because these assemblies should also have knowledge of the data access level, which, in turn, must know the types of entities that it should be displayed )

I solved this problem by introducing the CommonObjects project, in which I now save all my abstract classes and deprive the specific descendants (containing logic, etc.) of these base classes in the specific projects that are responsible for them (see: The decision on circular dependencies )

It compiled, and everything seemed to match the way I imagined it. But now it turns out that the Entity Framework seems to be struggling with derivatives located in a different assembly than the base classes.

At run time, when trying to access DbContext for the first time, the compiler threw an InvalidOperationException, saying:

The abstract type "Foo.Bar.AbstractClass" has no mapped children and therefore cannot be matched. Either remove the 'Foo.Bar.AbstractClass' from the model or add one or more types derived from 'Foo.Bar.AbstractClass' to the model.

Thus, EF, obviously, cannot find descendants, since it knows only the base classes (which are in the CommonObjects project), but the descendants are in a different assembly.

DbSet<AbstractClass> AbstractClasses { get; set; } 

According to this question: First and several assemblies of Entity Framework code I tried to add the following code to the constructor of my derived DbContext:

 ((IObjectContextAdapter)this).ObjectContext.MetadataWorkspace.LoadFromAssembly( Assembly.Load("Foo1")); 

But that did not work for me. When debugging and viewing MetadataWorkspace, the LoadFromAssembly method did not explicitly affect MetadataWorkspace and its elements (types were not loaded from the Foo1 assembly).

What am I missing here?

Thanks for your answers in advance.

Ben

+4
source share
1 answer

EDIT: this only works and is not worth it, and does not work at all if you use CodeFirst.

At first I ran into the same problem with the code. I tried your reflection method. This seems a bit uncomfortable, but you can trick EF into being fine with your setup with the inner class.

  internal class ClassToMakeEFHappy : AbstractClass {} 

I just created this in the same file as the AbstractClass definition, and it did the trick.

+1
source

All Articles