[英]Entity Framework 6 -> Use one property for two composite foreign keys
背景:我们正在从外部系统接收数据,该数据将存储在数据库中,并且模型基于从它们那里获得的信息。
一切都顺利进行,除了一个模型使用一个属性作为两种不同关系的复合外键。
以下代码将生成错误Duplicate 'ForeignKey' attribute
。 如果我从BusinessSystemId
删除ForeignKey
属性之一,则将收到错误消息The number of properties in the Dependent and Principal Roles in a relationship constraint must be identical.
我认为代码清楚地表明了我无法实现的目标。 也就是说,将BusinessSystemId
用作TPCaseName
两个单独的外键。
public class TPCase
{
[Key, Column(Order = 0)]
public string BusinessSystemId { get; set; }
[Key, Column(Order = 1)]
public int CaseId { get; set; }
public virtual ICollection<TPCaseName> CaseNames { get; set; }
}
public class TPCaseName
{
[Key, Column(Order = 0)]
[ForeignKey("TPCase")]
[ForeignKey("TPName")]
public string BusinessSystemId { get; set; }
[Key, Column(Order = 1)]
[ForeignKey("TPCase")]
public int CaseId { get; set; }
[InverseProperty("CaseNames")]
public virtual TPCase TPCase { get; set; }
[Key, Column(Order = 2)]
[ForeignKey("TPName")]
public int NameNo { get; set; }
public virtual TPName TPName { get; set; }
[Key, Column(Order = 3)]
[ForeignKey("TPNameType")]
public string NameType { get; set; }
public virtual TPNameType TPNameType { get; set; }
public string ContactName { get; set; }
}
public class TPName
{
[Key, Column(Order = 0)]
public string BusinessSystemId { get; set; }
[Key, Column(Order = 1)]
public int NameNo { get; set; }
public string NameCode { get; set; }
}
我可以通过将以下属性添加到TPCaseName
来解决此问题,但是由于该信息已经存在于BusinessSystemId
因此似乎没有必要。
[ForeignKey("TPName"), Column(Order = x)]
public string BusinessSystemId2 { get; set; }
我试图搜索具有相同情况的问题,但未发现任何问题。
您只需要注释Navigation属性即可指定复合外键。 例如
public class TPCase
{
[Key, Column(Order = 0)]
public string BusinessSystemId { get; set; }
[Key, Column(Order = 1)]
public int CaseId { get; set; }
public virtual ICollection<TPCaseName> CaseNames { get; set; }
}
public class TPCaseName
{
[Key, Column(Order = 0)]
public string BusinessSystemId { get; set; }
[Key, Column(Order = 1)]
public int CaseId { get; set; }
[Key, Column(Order = 2)]
public int NameNo { get; set; }
[Key, Column(Order = 3)]
public string NameType { get; set; }
[ForeignKey("BusinessSystemId,CaseId")]
public virtual TPCase TPCase { get; set; }
[ForeignKey("BusinessSystemId,NameNo")]
public virtual TPName TPName { get; set; }
//[ForeignKey("NameType")]
// public virtual TPNameType TPNameType { get; set; }
public string ContactName { get; set; }
}
public class TPName
{
[Key, Column(Order = 0)]
public string BusinessSystemId { get; set; }
[Key, Column(Order = 1)]
public int NameNo { get; set; }
public string NameCode { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.