使用TPT错误的EF 6具有相同的主键值

时间:2014-11-06 02:46:23

标签: c# entity-framework inheritance

我对TPT + EF6有一个很大的疑问。

在我的数据库模型中,我有一个表Person(我的应用程序中人员的基本信息),我有SupplierConsumer的表格。

我的课程是:

//to table dbo.Person
public class Person 
{
    public long Id {get; set;} //is pk
    public string Name {get; set;}
}

//to table dbo.Supplier
public class Supplier : Person
{
    public long Id {get; set;}//is pk and fk
    public string ProductName {get; set;}
}

//to table dbo.Consumer
public class Consumer 
{
    public long Id {get; set;} //is pk and fk
    public string budget {get; set;}
}

如果我有一个既是供应商又是消费者的人,我从相同/不同的DBContext获取记录或从另一个实体导航,那么EF会抛出异常:

  

EntitySet Person中的所有对象都必须具有唯一的主键。但是,类型为Supplier的实例和类型为Consumer的实例都具有相同的主键值EntitySet=Person;ID=20

有没有办法在TPT继承中指定一个鉴别器? 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我建议您实际需要的模式是每个具体类的表

as illustrated by this SQL Server diagram

这可以通过

实现
scope :available_for_user, -> (user_id) { joins(:collaborations).where.not(collaborations: {user_id: user_id}) }

请记住将以下内容放入您的dbcontext

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

    public  Supplier Supplier { get; set; }

    public  Consumer Consumer { get; set; }


}

public class Supplier
{
    public int Id { get; set; }
    public string ProductName { get; set; }
}

public class Consumer
{
    public int Id { get; set; }
    public string Budget { get; set; }
}
相关问题