Given the model:
public abstract class Person
{
public int Id {get;set;}
}
public class Customer : Person
{
public string Name {get;set;}
}
public class User : Person
{
public string Password {get;set;}
}
I need to add a customer and an user that refers to the same person
context.Set<Customer>().Add(new Customer { Name = "X" });
context.SaveChanges();
Now I have 2 entries in my db
Persons
Id: 1
Customers
Id: 1
Name: X
When I try to add the user to the person 1
context.Set<Customer>().Add(new User { Id = 1, Password = "0" });
context.SaveChanges();
Entity Framework ignores Id = 1 and create a new person.
How to get this to work?
This makes no sense because customer and user do not refer to a person, they are a person. If you have an object of type
Customerand another object of typeUserthere is no third identity calledPerson. There are only two identities and both have properties inherited from thePersonbase class.If you have that situation in your domain that a person can be a customer and a user at the same time modeling this with an inheritance hierarchy is not the ideal approach. You should better have a reference in both classes pointing to a person, like so: