【问题标题】:Entity Framework 6.1.3 :Set unique key constraint to a columnEntity Framework 6.1.3:为列设置唯一键约束
【发布时间】:2016-07-12 21:10:22
【问题描述】:

我在 VS2015 中开发的应用程序中使用最新版本的实体框架和代码优先方法。

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

我试过这个:

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

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

请指导我。

谢谢。

【问题讨论】:

  • 很奇怪,还有你为什么使用order:1,你的索引是composite吗?如果没有,请尝试从索引声明中排除订单。
  • 多列索引使得这些列的组合是唯一的,而不是索引的每个单独的列

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


【解决方案1】:

我们正在使用以下扩展方法:

/// <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中这样称呼它:

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

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

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

【讨论】:

    猜你喜欢
    • 2019-04-19
    • 1970-01-01
    • 2015-01-06
    • 1970-01-01
    • 2012-08-02
    • 2018-09-28
    • 2021-04-10
    • 2017-05-05
    • 1970-01-01
    相关资源
    最近更新 更多