[英]Entity Framework relations questions
I have three classes 我有三节课
public class SPR
{
public int ID { get; set; }
public string SubmittedBy { get; set; }
public virtual ICollection<SPRItem> AllItems { get; set; }
}
public class SPRItem
{
[Key]
public int ID { get; set; }
public string manufacturer { get; set; }
[ForeignKey("SPRItemDetails")]
public virtual SPRItemDetails ItemDetails { get; set; }
public string requestedMinimumQuantity { get; set; }
public virtual SPR SPR { get; set; }
}
public class SPRItemDetails
{
public int ID { get; set; }
public string ItemNumber { get; set; }
public virtual SPRItem SPRItem { get; set; }
}
So the SPR class has a collection of SPRItem and which has the ItemDetails object. 所以SPR类有一个SPRItem集合,它有ItemDetails对象。
I have a web API method which maps the data to the SPR object and fills in the SPRItem list and ItemDetails object. 我有一个Web API方法,它将数据映射到SPR对象并填充SPRItem列表和ItemDetails对象。 But whenever I am trying to save it using Entity Framework code first I am getting this error
但每当我尝试使用Entity Framework代码保存它时,我就会收到此错误
{"Message":"An error has occurred.","ExceptionMessage":"Unable to determine the principal end of an association between the types 'SharePoint.MultiSPR.Service.Models.SPRItemDetails' and 'SharePoint.MultiSPR.Service.Models.SPRItem'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
This is my Context 这是我的背景
public System.Data.Entity.DbSet<SharePoint.MultiSPR.Service.Models.SPR> SPRs { get; set; }
public System.Data.Entity.DbSet<SharePoint.MultiSPR.Service.Models.SPRItem> SPRItem { get; set; }
public System.Data.Entity.DbSet<SharePoint.MultiSPR.Service.Models.SPRItemDetails> SPRItemDetails { get; set; }
Can someone please tell me how to configure the relations correctly. 有人可以告诉我如何正确配置关系。
Thanks 谢谢
In a 1:1 relation you always have to indicate the principal and the dependent entity. 在1:1关系中,您始终必须指明委托人和从属实体。 The principal entity is the one that is most independent of the other, in this case
SPRItem
, presumably. 主要实体是最独立于另一个实体的实体,在这种情况下可能是
SPRItem
。
Next thing to decide is whether the relationship should be optional or required. 接下来要决定的是关系应该是可选的还是必需的。 I think, judging by the entity names, an
SPRItemDetails
will never exist without an SPRItem
, so the relationship is 1:0..1
(not 0..1:0..1
). 我认为,根据实体名称判断,如果没有
SPRItem
, SPRItemDetails
将永远不存在,因此关系为1:0..1
(不是0..1:0..1
)。 Here's how to configure that: 以下是配置:
modelBuilder.Entity<SPRItem>()
.HasOptional(si => si.ItemDetails)
.WithRequired(id => id.SPRItem);
This creates (or requires) an SPRItemDetails
table having a primary key that's also a foreign key to SPRItem
. 这创建(或要求)具有主键的
SPRItemDetails
表,该主键也是SPRItem
的外键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.