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

问题描述:

我在VS2015中开发的应用程序中使用最新版本的实体框架和代码优先方法。实体框架6.1.3:为列设置唯一键约束

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

我已经试过这样:

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

,但它无法正常工作。在Customer表中,列EmailAddress应该只有唯一的值,它应该允许重复。

请指导我。

谢谢。

+0

这是自叹不如,也就是为什么你使用顺序:1,是你的指数复合?如果不是,请尝试从索引声明中排除订单。 –

+0

多列索引使这些列的组合是唯一的,而不是索引的每个单独列 –

我们用下面的扩展方法:

/// <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");