Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework: Inheritance, change object type

Let's say, I have 2 classes in the model: User (mapped to USERS table) and PrivilegedUser (inherits User, additional info is stored in PRIVILEGEDUSERS table).

Now, I have a row in USERS (and instance of User) and need to convert that user to PrivilegedUser (i.e. to create a record in PRIVILEGEDUSERS with the same Id). Is there a way to do this without Delete/Insert?

The problem is you don't have PRIVILEGEDUSERS representation in the model, so you cannot create only that part of PrivilegedUser.


It was just an example. PrivilegedUser may have some discount or personal manager or whatever in addition to ordinary User properties. In the same time, there are other tables which need to reference users regardless of concrete User type. I've implemented it using Table-per-Type inheritance mode. In the database level it's very simple to convert users from one type to another (you just need to insert or delete record from extension table). But in EF you have only UserSet which stores both User and PrivilegedUser objects. That's why I ask is it possible to replace existing User object with PrivilegedUser keeping existing Id and without deleting record from USERS table.

like image 336
Ruslan Minasian Avatar asked Aug 06 '09 15:08

Ruslan Minasian


2 Answers

No you cannot.

As explained by this article, EF (3.5) does not support this feature. You must use stored procedure to accomplish this.

like image 176
Tri Q Tran Avatar answered Nov 16 '22 20:11

Tri Q Tran


You need to change your world view. Your view is that you have standard users with standard privileges and super users with additional privileges. The privileges aren't enumerated, they are implicit.

The new world view is that you maintain a list of all privileges, both standard and super and then in a mapping table you create a many to many map of which users have which privileges. When a user is granted super privileges, you just add mappings for the appropriate privileges to the mapping table. You don't need a PrivilegedUser class, just a list of privileges in the User class. The privileges may be either standard or super.

like image 26
J Edward Ellis Avatar answered Nov 16 '22 20:11

J Edward Ellis