Question

I'm using EF 4.3 with CodeFirst and I have a supertype/subtype model similar to this one:

public Person {
    long Id { get; set; }
    [Required]
    string Name { get; set; }
}
public Costumer : Person {
    string SomeData { get; set; }
    [Required]
    string SomeRequiredData { get; set; }
}

This is a simplified version of the problem. The tables have several fields. A person can be a "promoted" to Costumer later in the application. So Person is created first and then transformed to Customer.

The question is: After I create Person how can I "promote" it to Vendor without creating (or recreating) a new Person record? If I do:

var costumer = new Costumer { 
    Id = [same id used before when Person was created], 
    SomeRequiredData = "Data"  
};

The model gives an error saying that Name is required. I should not be required to repeat all required info from Person in the new Vendor instance since it's already there in the original Person record.

Can anybody help?

P.S. The model is configured to create 2 separate tables, one for each class...

Was it helpful?

Solution

After I create Person how can I "promote" it to Vendor without creating (or recreating) a new Person record?

You most can't with EF because you cannot change the type of existing instance (you cannot cast Person to Customer). Because you cannot cast the entity you also cannot update its type in the database with EF. In the same time you cannot insert Customer instance with existing Id because this operation expect inserting both parent and child type (remember Customer is a Person in your model and because of that inserting Customer means inserting Person as well).

The reason why it doesn't work is that your domain model is wrong. You should not have Customer as subtype of the Person because in OOP it means exactly what happened now - you cannot change person to customer without creating a new person instance (because customer is a person). To support this scenario you must have only Person entity and this entity must have property describing its type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top