C# 如何在代码优先实体框架fluent API中指定多列唯一约束
假设我有以下实体:C# 如何在代码优先实体框架fluent API中指定多列唯一约束,c#,entity-framework,ef-fluent-api,C#,Entity Framework,Ef 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;} } 然而,当实体框架自动创建表时
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;}
}
然而,当实体框架自动创建表时,它不会知道我想要这个。如何在fluent API中指定此选项?请参阅
在映射类中,假设它从EntityTypeConfiguration
扩展,则需要使用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 }));
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 }));