views:

56

answers:

2

Hello everyone,

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?

Regards.

+2  A: 

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>().

Alex James
+1  A: 

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

Thomas Levesque