1
votes

I'm using EF5 and Code-First.

I have an abstract base class called FooBase. Foo1 and Foo2 both inherit from FooBase. I use EF's mapping configuration based on a Discriminator called Bar. So if Bar = someValue, create Foo1... if Bar is anotherValue, create Foo2.

Since Bar is a discriminator, I don't have access to it as a property on any of the Foo classes.

I now have the need to convert an instance of Foo1 to Foo2. I use reflection and move the properites to the new instance, including Foo1's key value. It's an exact duplicate, except that it is a different type. I change the EntityState to modified and save to the database.

However, the discriminator value in the database is not getting updated. It still remains the same value as if it was still Foo1.

I can guess that since the enitity is only set to modified, EF doesn't bother checking the discriminator.

Does anyone know a way around this?

1

1 Answers

2
votes

You cannot change existing instance to another type. Type of the entity associated with key value is immutable. If you want to create Foo2 from Foo1 you need to create a new instance with a new key value and insert it to database. Just modifying will always keep the key and discriminator.

If you seriously need to change the type and keep the key inheritance is not solution for you. Think about the key as equivalent to reference and about discriminator as equivalent to type in .NET - you cannot change type of existing reference.