EF - generic "AddOrUpdate" method suddenly breaks

I am using Entity Framework 4 (database approach) in my ASP.NET 4.0 Webforms application.

What I basically do is select the object to be edited from mine ObjectContext

and display the fields where the user has to enter data (or modify existing data) in the web form.

When it comes time to store the data, I read the values ​​from the web form, creating a new instance Entity

, and then I have a generic method AddOrUpdate

that determines if it is a new object (so it needs to be inserted), or if it already exists (so it need to update existing data).

My method using EntityKey

and checks to see if the context of an object is aware of that object, very similar to what Cesar de la Torre from Microsoft shows here in his blog post:

public static void AddOrUpdate(ObjectContext context, EntityObject objectDetached)
{
    if (objectDetached.EntityState == EntityState.Detached)
    {
        object currentEntityInDb = null;

        if (context.TryGetObjectByKey(objectDetached.EntityKey, out currentEntityInDb))
        {
            // attach and update the existing entity
        }
        else
        {
            // insert new entity into entity set
            context.AddObject(objectDetached.EntityKey.EntitySetName, objectDetached);
        } 
    }
}

      

It worked really well - for the longest time. But today, all of a sudden, unexpectedly, I keep getting exceptions like this in the statement context.TryGetObjectByKey

:

System.InvalidOperationException: Object mapping could not be found for type with identifier 'MyEntityType'

I don't remember that I changed anything at all in this key code - and the entity type is defined, the value ID

that is stored in EntityKey

does exist in the database ... everything should be fine, but it keeps failing on me ...

What happened here?

I found several blog posts and forums on this topic, but no one could really enlighten me or help me fix this issue. I must have messed up something - bad - but I really can't see the forest for the trees - any hints?

+3


source to share


1 answer


Typically, this problem occurs when EF cannot find an assembly with a type. Since the complete exception is difficult to pinpoint exactly, it seems that your recent changes and the way you use EF seem to be the cause.

EF ususally picks a type directly from the type itself when it has to access it using an ObjectSet in context. In other cases, when the type is not available from the calling context, it looks at the calling assembly and any DLL referenced by the calling assembly. Id it can't find it, it throws an error message.

In the MetadataWorkspace context.



ObjectContext.MetadataWorkspace.LoadFromAssembly (assembly).

This way, EF will know where to look for your types.

+1


source







All Articles