yeomandev
yeomandev

Reputation: 11806

How to change the auto-generated "Discriminator" column in EntityFramework?

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.

Upvotes: 5

Views: 4462

Answers (1)

Craig Stuntz
Craig Stuntz

Reputation: 126587

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 User object and an Administrator object, rather than wanting to replace the User object with an Administrator subtype.

I wrote about this idea in an old blog post:

One of the mental barriers that you have to get over when designing a good object relational mapping is the tendency to think primarily in object oriented terms, or relational terms, whichever suits your personality. A good object relational mapping, though, incorporates both a good object model and a good relational model. For example, let’s say you have a database with a table for People, and related tables for Employees and Customers. A single person might have a record in all three tables. Now, from a strictly relational point of view, you could construct a database VIEW for employees and another one for customers, both of which incorporate information from the People table. When using a one VIEW or the other, you can temporarily think of an individual person as "just" an Employee or "just" a Customer, even though you know that they are both. So someone coming from this worldview might be tempted to do an OO mapping where Employee and Customer are both (direct) subclasses of Person. But this doesn’t work with the data we have; since a single person has both employee and customer records (and since no Person instance can be of the concrete subtype Employee and Customer simultaneously), the OO relationship between Person and Employee needs to be composition rather than inheritance, and similarly for Person and Customer.

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.

Upvotes: 7

Related Questions