I have a project where I\'ve defined in EF an Employer
as a derived class of User
. In my process I create a user without knowing whether it will e
Supose that your Employer entity has only nullable properties then it is possible to go to the table at the database and change the Discriminator from User to Employer. All relationships will be kept. And also it is possible to do the opposite.
It is not possible. You must always use final type. Once you create it as a User
, EF will never allow you changing it to a derived entity type.
Btw. it is also not possible with object oriented approach as well. You cannot cast instance of parent class to the instance of derived class (unless it really is instance of derived class) - it will throw exception at runtime. Very simple example to reproduce the issue:
class X { }
class Y : X { }
class Program
{
static void Main(string[] args)
{
X x1 = new Y();
Y y1 = (Y)x1; // Works
X x2 = new X();
Y y2 = (Y)x2; // InvalidCastException
}
}
The only way to do that is overriding conversion operator which will internally create a new instance of derived class and copy all fields from the old parent instance to that new derived one.
Exactly the same approach is needed with entity framework. If you started with User
entity and now you want to promote it to Employer
entity you must delete old user and create new Employer
.