Downcasting with Entity Framework

后端 未结 2 515
醉梦人生
醉梦人生 2020-12-11 23:19

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

相关标签:
2条回答
  • 2020-12-12 00:02

    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.

    0 讨论(0)
  • 2020-12-12 00:10

    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.

    0 讨论(0)
提交回复
热议问题