开发者

EF 4.0 problem adding object to the context

开发者 https://www.devze.com 2022-12-16 14:20 出处:网络
I have made a generic save function for EF: public void Save(T entity) { using (C context = new C()) { string entitySetName = context.FindEntitySetByEntity<T>();

I have made a generic save function for EF:

public void Save(T entity)
    {
        using (C context = new C())
        {
            string entitySetName = context.FindEntitySetByEntity<T>();

            T entityInDDBB = GetEntityByKey(entity, entitySetName, context);

            //if we didn't find the entity in database make an insert, if not an update.
            if (entityInDDBB == null)
            {

                **context.AddObject(entitySetName, entity);**
            }
            else
            {
                context.ApplyCurrentValues(entitySetName,  entity);
            }

            context.SaveChanges();
        }
    } 

The problem is that if we pass a derived type to AddObject (f.e: teacher) but the mapping expects Person it throws an error.

How could I change the type to the object (I suppose it is impossible without creating a new one) or do you know any other way to make it work?

开发者_如何学C

Regards.


Well EF doesn't allow you to treat one CLR class as another.

i.e. you can't treat Teacher as Person.

Given that limitation Teacher must be an Entity too, if not this will always fail.

But from your description it sounds like you don't have a Teacher Entity or mapping information for Teacher?

Unfortunately there is no way around that.

Alex

NOTE: your code should work fine if you have a teacher entity and mappings and if FindEntitySetByEntity<Teacher>() returns the same as FindEntitySetByEntity<Person>().


Make sure you correctly defined the inheritance relation in the entity data model. Here's a good article about it :

http://blogs.msdn.com/adonet/archive/2007/03/15/inheritance-in-the-entity-framework.aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消