实体框架6.1.3:将唯一键约束设置为列

时间:2016-03-25 05:12:55

标签: c# entity-framework unique-constraint unique-key

我在我的应用程序中使用最新版本的Entity Framework和代码优先方法,我在VS2015中开发。

在我的一个实体集(Customer)中,我想在列EmailAddress上设置一个唯一的键约束。

我试过这个:

[Index("IX_EmailAddress", 1, IsUnique = true)]

但它不起作用。在Customer表中,列EmailAddress应该只包含唯一值,它应该允许重复。

请指导我。

谢谢。

1 个答案:

答案 0 :(得分:2)

我们使用以下扩展方法:

/// <summary>
/// Method to add a unique constraint to a property of an entity.
/// The unique constraint name is usually "UI_{classname}_{propertyname}".
/// </summary>
/// <param name="prop">The property for which a unique constraint is added</param>
/// <param name="constraintName">The name of the constraint</param>
/// <param name="constraintOrder">
///     Optional constraint order for multi column constraints.
///     This can be used if <see cref="HasUniqueConstraint"/> is called for multiple properties to define the order of the columns.
/// </param>
public static void HasUniqueConstraint(this PrimitivePropertyConfiguration prop, string constraintName, int constraintOrder = 1) {
    prop.HasColumnAnnotation(IndexAnnotation.AnnotationName,
        new IndexAnnotation(new IndexAttribute(constraintName, constraintOrder) {
            IsUnique = true
        })
    );
}

我们在模型构建器中调用它如下:

 ModelBuilder.Entity<Customer>().Property(c => c.EmailAddress ).HasUniqueConstraint("IX_EmailAddress");

但我不确定这与您使用的属性是否不同。 无论如何,在应用此之后,您应该在生成的迁移中看到以下语句:

 CreateIndex("dbo.Customer", "EmailAddress ", unique: true, name: "IX_EmailAddress");