首页 > 解决方案 > 使用 Entity Framework Fluent API 的带有 where 子句的唯一索引

问题描述

有没有办法使用实体框架指定多列唯一性约束?

这是我想要的约束

CREATE UNIQUE NONCLUSTERED INDEX myconstraint
ON myTable(col1,col2)
WHERE col2 IS NOT NULL;

下面的代码让我了解了 Entity Framework Fluent API 的大部分内容,但由于它不允许空值(即,两个空值col2将被视为违反约束,而我希望它允许多个空值),所以它不够。

modelBuilder.Entity<myTable>().Property(x => x.col1)
    .HasColumnAnnotation(IndexAnnotation.AnnotationName,
    new IndexAnnotation(new IndexAttribute("myconstraint", 0) { IsUnique = true }));
modelBuilder.Entity<myTable>().Property(x => x.col2)
    .HasColumnAnnotation(IndexAnnotation.AnnotationName,
    new IndexAnnotation(new IndexAttribute("myconstraint", 1) { IsUnique = true }));

标签: sql-serverentity-frameworkef-fluent-api

解决方案


推荐阅读