5

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.

David Russell
  • 623
  • 6
  • 16
  • 1
    Why can't you still call that function? I've not actuaqlly checked, but based on some quick searching you should be able to access the `MetadataWorkspace` from your `DbContext` using `dbContext.MetadatWorkspace`. Does that not work? – Kevin Cathcart Mar 21 '11 at 14:59
  • Yes, you can cast DbContext to IObjectContextAdapter and retrieve it's underlying ObjectContext (See: http://weblogs.asp.net/jgalloway/archive/2011/01/21/fix-wcf-data-service-with-entity-framework-code-first-dbcontext-doesn-t-accept-updates.aspx). – David Russell Mar 23 '11 at 10:01
  • That allowed me to try MetadataWorkspace.LoadFromAssembly() but it didn't fix my problem :( – David Russell Mar 23 '11 at 10:01

3 Answers3

3

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.

David Russell
  • 623
  • 6
  • 16
2

I know this post is a bit old, but I was able to accomplish this using @Dave's recomendation inside the constructor:

public Context() {
    ((IObjectContextAdapter)this).ObjectContext.MetadataWorkspace.LoadFromAssembly(
        System.Reflection.Assembly.GetAssembly(
             typeof(--[Inherited DbContext]--)));
}
Scott Stafford
  • 43,764
  • 28
  • 129
  • 177
kroehre
  • 1,104
  • 5
  • 15
1

I'm quite new to EF (Entity Framework 4) and I got the same exception when I made changes in the model.

My problem turned out to be that I did not know EF need all the names on all the navigation properties to agree, not only their type. For example if there is a navigation property named foo, then there needs to be a declared variable in the corresponding class with the very same name.

Tariqulazam
  • 4,535
  • 1
  • 34
  • 42
John
  • 55
  • 7