[英]Entity Framework - How to apply constraint to model properties?
我正在使用Entity Framework 6.1.3
并具有如下所示的两个模型。 但是,当我运行迁移时,出现以下错误:
无法确定类型“ Example.Models.GiftVoucher”和“ Example.Models.Payment”之间的关联的主要终点。 必须使用关系流利的API或数据注释显式配置此关联的主要端。
我已经搜索过,发现了这个问题 。 解决方案之一是使用Required
属性。
但是,我不知道如何在实体框架中执行以下操作:
Purchase_Id
和Redemption_Id
外键,如图所示。 CONSTRAINT fk-giftvoucher-table FOREIGN KEY (Purchase_Id) REFERENCES PAYMENT (PaymentId)
。 付款方式
public class Payment {
public int Id { get; set; }
[Required]
public DateTime DateTime { get; set; }
public double Amount { get; set; }
[Required]
public int GiftVoucherId { get; set; }
public GiftVoucher GiftVoucher { get; set; }
}
礼券模型
public class GiftVoucher
{
public int Id { get; set; }
public double Amount { get; set; }
[Required]
public int PaymentId { get; set; }
public Payment Payment { get; set; }
}
我不会经常使用一对一的关系...除非我想垂直分区以满足性能需求,或者有迫切的OCD需要分离这些关注点。
*注意 :从技术上讲,SQL Server中不可能建立一对一关系。 它将始终为一对零或一 。 EF在不在数据库中的实体上形成一对一关系。*
但是,文档是您的朋友
在大多数情况下,实体框架可以推断出哪种类型是从属类型以及哪种是关系中的主体。 但是,当关系的两端都是必需的,或者双方都是可选的时, 实体框架就无法识别从属和委托人 。 当需要关系的两端时,
WithRequiredDependent
在HasRequired
方法之后使用WithRequiredPrincipal
或WithRequiredDependent
。 ...
鉴于以下
public class GiftVoucher
{
// your primary key
public int GiftVoucherId { get; set; }
public virtual Payment Payment { get; set; }
// other properties
public double Amount { get; set; }
}
public class Payment
{
// We need to share the same key
public int GiftVoucherId { get; set; }
public virtual GiftVoucher GiftVoucher { get; set; }
// other properties
public DateTime DateTime { get; set; }
public double Amount { get; set; }
}
我们可以像这样使用Fluent API
// Configure the primary key for the OfficeAssignment
modelBuilder.Entity<Payment>()
.HasKey(t => t.GiftVoucherId);
// we are essentially making GiftVoucher the principle in the DB
modelBuilder.Entity<GiftVoucher>()
.HasRequired(t => t.Payment)
.WithRequiredPrincipal(t => t.GiftVoucher);
所以基本上HasRequired
正在GiftVoucher
需要和WithRequiredPrincipal
正在Payment
需要..反过来,EF将抛出,如果上面的不满意
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.