【发布时间】:2016-06-22 18:35:28
【问题描述】:
在我的模型中,我有一个带有自关联的 [Customer] 表:
1 [客户] 可能有 1 [赞助商],赞助商是客户。
在 EF 6 中,我想知道是否可以将实体 Customer 拆分为两个单独的实体 [Customer] 和 [Sponsor] 并为它们分配同一个表?
谢谢
【问题讨论】:
标签: asp.net entity-framework visual-studio
在我的模型中,我有一个带有自关联的 [Customer] 表:
1 [客户] 可能有 1 [赞助商],赞助商是客户。
在 EF 6 中,我想知道是否可以将实体 Customer 拆分为两个单独的实体 [Customer] 和 [Sponsor] 并为它们分配同一个表?
谢谢
【问题讨论】:
标签: asp.net entity-framework visual-studio
你可以继承实体来做一个别名考虑这个例子:
public class Person
{
public int ID {get;set;}
// your shared properties here
}
public class Customer: Person
{
// additional properties such as
public virtual Sponsor Sponsor {get;set;}
}
public class Sponsor : Person
{
// this could be have own properties or not
}
现在你的DbContext 可能是这样的:
public class MyDbContext:DbContext
{
public IDbSet<Person> Persons{get;set;}
// optionally you could add child objects
public IDbSet<Customer> Customers{get;set;}
public IDbSet<Sponsor> Sponsors{get;set;}
}
由于使用继承EF,只需为您的实体创建一个表。但是你有 3 个单独的班级。
【讨论】:
是的,你可以
public class Customer
{
public int ID {get;set;}
//all your columns goes here
///these 2 lines for foreign key mapping except sponsor
public virtual Customer Sponsor {get;set;}
public virtual IList<Customer> CustomerList{get;set;}
}
在你的 DbContext 中
public DbSet<Customer> Customers{get;set;}
【讨论】: