如何使用数据注释在 EF 7 Code First 中指定唯一键

How to specify Unique Key in EF 7 Code First with Data Annotations

您可以使用 Fluent 指定唯一键 Api:

public class MyContext : DbContext
{
    public DbSet<User> Users { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>()
            .HasIndex(u => u.Nickname)
            .IsUnique();
    }
}

public class User
{
    public int UserId { get; set; }
    public string Nickname { get; set; }
}

但是你可以用数据注释来做吗?

编辑

EF7 Beta 8 中的方法更改:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<User>()
        .Index(u => u.Nickname)
        .Unique();
}

恐怕 EF 7 仍不支持使用数据注释创建 Index。检查此 link

我也试图在最新版本中找到与该主题相关的一些信息,但找不到任何信息。

EF 7 beta 8 release notes

EF 7 RC1 release notes

我现在发现 post 一位 EF 开发人员 (divega) 是这样说的:

In EF7 we support defining indexes using the fluent API but not an attribute, at least no yet. The IndexAttribute you are possibly referring to is something we added to the EF 6.x package at some point but never really became a standard DataAnnotation.

We don't want to copy the original attribute from EF6 as is because there are a few things in it that we would like to change. Also, having it in DataAnnotations directly would likely make more sense than adding it to the EF7 package. I should mention though that it is highly unlikely that we will add IndexAttribute in the EF7 RTM timeframe.

更新 1

显然,这是不会添加到 EF Core 的功能,至少目前不会。

来自EF Core documentation

Indexes can not be configured using Data Annotations.

但是你可以使用 Fluent Api:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Blog>()
        .HasIndex(b => b.Url)
        .HasName("Index_Url");
}

在没有内置支持的情况下,您可以使用自己的自定义属性来注释模型属性并应用于OnModelCreating():

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    foreach (var entity in modelBuilder.Model.GetEntityTypes())
    {
        foreach (var prop in entity.GetProperties())
        {
            var index = prop.PropertyInfo.GetCustomAttribute<IndexAttribute>();
            if (index != null)
            {
                entity.AddIndex(prop);
            }
        }
    }
}

使用简单的标记属性class:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class IndexAttribute : Attribute
{
}

然后在你的模型中class,只需添加创建二级索引的属性:

public class User
{
    public int UserId { get; set; }
    [Index]
    public string Nickname { get; set; }
}