如何在代码优先的Entity Framework流利API中指定多列UNIQUE约束 [英] How to specify a multi-column UNIQUE constraint in code-first Entity Framework fluent API
问题描述
假设我有以下实体:
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;}
}
这是与<$ c的一对多关系$ c> CalendarID 作为外键。问题是我还想确保每个日期在每个日历中仅存在一次。也就是说,没有两天都有相同的 Date
和相同的 CalendarID
。在原始SQL中,我可以通过以下方式做到这一点:
This is a one-to-many relationship with CalendarID
as a foreign key. The issue is I also want to make sure that each date exists only once in each calendar. That is, no two days have both the same Date
and same CalendarID
. In raw SQL I can do this by:
ALTER TABLE Days
ADD CONSTRAINT UN_Day UNIQUE ([Date],CalendarID);
但是,Entity Framework在自动创建表格时不知道我要这个。如何在fluent API中指定它?
However, Entity Framework won't know I want this when it creates the table automatically. How can I specify this in the fluent API?
推荐答案
请参见在一个或多个属性上配置索引。
在您的映射类中,假设它从 EntityTypeConfiguration< Day>
扩展,则需要添加使用System.Data.Entity.Infrastructure.Annotations;
并执行以下操作:
In your mapping class, assuming it extends from EntityTypeConfiguration<Day>
then you will need to add using System.Data.Entity.Infrastructure.Annotations;
and do the following:
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 }));
这篇关于如何在代码优先的Entity Framework流利API中指定多列UNIQUE约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!