I have a base class and there are derived classes. The base class is mapped to a table using EF4 TPH(Table-per-hierarchy). In my application, the user can select one of the many derived classes and then I need to save them with the “Discriminator” column correctly populated.
On the UI the user enters Id & Name only (base class properties) and hence I am storing user entries in a list of base class objects. Since I get to know which derived type the user has selected at run time, I am not sure how to do this.
So far I’ve tried using Convert.ChangeType on the base objects to get the derived class object and then doing an Add to the entity. But it fails with “Object must implement IConvertible.”
Not sure what else can I do. Any ideas? Thanks.
Use
var derivedEntity = Activator.CreateInstance(typeof(YourDerivedType));then attach it.Or better still, let entity framework do it for you:
Where
Contextis yourDbContext.