Pablo Castilla
Pablo Castilla

Reputation: 2741

EF 4.0 problem adding object to the context

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.

Upvotes: 0

Views: 364

Answers (2)

Thomas Levesque
Thomas Levesque

Reputation: 292405

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

Upvotes: 1

Alex James
Alex James

Reputation: 20924

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

Upvotes: 2

Related Questions