Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Code First and Multiple Assemblies

I have a subclass in a different assembly to its base class. The parent is a POCO class used for EF Code First.

When I try to add an instance of inherited class to the database I get InvalidOperationException: "Object mapping could not be found for Type with identity 'Foo.Bar.MyInheritedClass'".

It works fine if subclass is in same assembly as base class.

In regular EF the solution seems to be a call to ObjectContext.MetadataWorkspace.LoadFromAssembly(assembly). But I can't figure out how this relates to Code First.

Any advice?

I'm using Entity Framework 4.1 RC.

like image 625
David Russell Avatar asked Mar 21 '11 14:03

David Russell


People also ask

How do I code first in Entity Framework?

Step 1 − First, create the console application from File → New → Project… Step 2 − Select Windows from the left pane and Console Application from the template pane. Step 3 − Enter EFCodeFirstDemo as the name and select OK. Step 4 − Right-click on your project in the solution explorer and select Manage NuGet Packages…

What is DbContext in Entity Framework?

A DbContext instance represents a combination of the Unit Of Work and Repository patterns such that it can be used to query from a database and group together changes that will then be written back to the store as a unit. DbContext is conceptually similar to ObjectContext.


1 Answers

I solved this by inheriting from the first assembliy's DbContext, adding a DbSet<> for the derived class, and then adding new instances of derived type to to that.

Posted code on MSDN forum here.

like image 184
David Russell Avatar answered Sep 28 '22 09:09

David Russell