繁体   English   中英

实体框架-如何将约束应用于模型属性?

[英]Entity Framework - How to apply constraint to model properties?

我正在使用Entity Framework 6.1.3并具有如下所示的两个模型。 但是,当我运行迁移时,出现以下错误:

无法确定类型“ Example.Models.GiftVoucher”和“ Example.Models.Payment”之间的关联的主要终点。 必须使用关系流利的API或数据注释显式配置此关联的主要端。

我已经搜索过,发现了这个问题 解决方案之一是使用Required属性。

但是,我不知道如何在实体框架中执行以下操作:

  • 重命名这两个模型中的GiftVoucherId和PaymentId,它们是Purchase_IdRedemption_Id外键,如图所示。
  • 然后在Entity Framework中执行等效的操作,例如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在不在数据库中的实体上形成一对一关系。*

但是,文档是您的朋友

配置需要两端(一对一)的关系

在大多数情况下,实体框架可以推断出哪种类型是从属类型以及哪种是关系中的主体。 但是,当关系的两端都是必需的,或者双方都是可选的时, 实体框架就无法识别从属和委托人 当需要关系的两端时, WithRequiredDependentHasRequired方法之后使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM