I am working on some code that makes use of single table inheritance via EF4.3.
There is an entity called User and another entity called Admin. Admin inherits from user.
User class
public class User
{
public int Id {get;set;}
public string Username {get;set;}
}
Admin class
public class Admin : User { }
EF generated the database tables with a Discriminator column. When an Admin record is added then Discriminator="Admin" and a User record would have Discriminator="User".
My question is, how do I update the Discriminator column if I want to make a User into and Admin?
I tried casting from one object type to the other and saving using EF. but that doesn’t change the Discriminator column. How do I change it?
Thanks for any help.
Objects can’t change their types, ever. If you intend to change the “administrator” setting for a user (reasonable), you should do that with an attribute/property, not a type name.
For example, you could have an association between a
Userobject and anAdministratorobject, rather than wanting to replace theUserobject with anAdministratorsubtype.I wrote about this idea in an old blog post:
To answer your question directly, there’s no way to change this column using EF. You could of course, do it in straight SQL. But for the reason given above, I’d encourage you to change this design.