【问题标题】:How to specify a multi-column UNIQUE constraint in code-first Entity Framework fluent API如何在代码优先实体框架流式 API 中指定多列 UNIQUE 约束
【发布时间】:2017-12-08 16:32:13
【问题描述】:

假设我有以下实体:

public class Calendar{
    public int ID{get;set;}
    public ICollection<Day> Days { get; set; }
}
public class Day{
    public int ID{get;set;}
    public DateTime Date{get;set;}
    public int CalendarID{get;set;}
}

这是一个以CalendarID 作为外键的一对多关系。问题是我还想确保每个日期在每个日历中只存在一次。也就是说,没有哪两天有相同的Date 和相同的CalendarID。在原始 SQL 中,我可以这样做:

ALTER TABLE Days
ADD CONSTRAINT UN_Day UNIQUE ([Date],CalendarID);

但是,Entity Framework 在自动创建表时不会知道我想要这个。如何在 fluent API 中指定这一点?

【问题讨论】:

    标签: c# entity-framework ef-fluent-api


    【解决方案1】:

    Configuring an Index on one or more properties

    在您的映射类中,假设它从EntityTypeConfiguration&lt;Day&gt; 扩展,那么您需要添加using System.Data.Entity.Infrastructure.Annotations; 并执行以下操作:

    this.Property(x => x.Date)
        .HasColumnAnnotation(IndexAnnotation.AnnotationName,
                     new IndexAnnotation(new IndexAttribute("UN_Day", 0) { IsUnique = true }));
    
    this.Property(x => x.CalendarID)
        .HasColumnAnnotation(IndexAnnotation.AnnotationName,
                     new IndexAnnotation(new IndexAttribute("UN_Day", 1) { IsUnique = true }));
    

    【讨论】:

    • 我没有HasColumnAnnotation(),但我看到了HasAnnotation()。那是相同方法的更新版本吗?我什至无法导入您提到的命名空间。显然,在System.Data.Entity.Infrastructure.Annotations 中已经找不到Entity。我检查了不同的 NuGet 包,但没有发现任何明显的东西。鉴于您的答案已有 3 年以上的历史,我怀疑语法可能会有所改变。无论如何 +1,但如果你有的话,我也很高兴获得更多最新信息。
    • HasAnnotation 看起来像 EF Core 等同于 HasColumnAnnotation
    猜你喜欢
    • 2021-01-05
    • 2023-03-12
    • 1970-01-01
    • 2018-04-06
    • 2015-05-26
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    相关资源
    最近更新 更多