开发者

Adding multiple inherited instances of different children types in a TPT Mapping EF4.1

开发者 https://www.devze.com 2023-04-13 09:44 出处:网络
Given the model: public abstract class Person { public int Id {get;set;} } public class Customer : Person

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 Passwor开发者_如何学运维d {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?


"I need to add a customer and an user that refers to the same person"

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 Customer and another object of type User there is no third identity called Person. There are only two identities and both have properties inherited from the Person base 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:

public class Person 
{
    public int Id {get;set;}
}

public class Customer
{
    public int Id {get;set;}
    public string Name {get;set;}
    public int PersonId {get;set;}
    public Person Person {get;set;}
}

public class User
{
    public int Id {get;set;}
    public string Password {get;set;}
    public int PersonId {get;set;}
    public Person Person {get;set;}
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号