Asp.net 核心 Entity Framework 找不到 IndexAttribute

Asp.net Core Entity Framework cannot find IndexAttribute

我在 Mac 上的 Visual Studio 代码中收到以下内容,在 IDE 和控制台 window 中执行 "dotnet run" 后:

找不到类型或命名空间名称'IndexAttribute'

我有一个名为 Story 的 class,我想将其用于通过 Code First 生成数据库。这个 class 有一个标有 KeyAttribute 的主键和标有 MaxLengthAttribute 的 Author 字符串,所以它们都有效(使用 System.ComponentModel.DataAnnotations)。另外两个字段 DateTime Date 和 bool IsPublished 应用了 IndexAttribute(这是一个两列索引)。我明确地将其命名为 IX_DatePublished,IsUnique = false,并将 Order = 1 用于 Date 字段,Order = 2 用于 IsPublished 字段。

谢谢!

我还在熟悉核心工具的过程中;进一步的研究表明不支持此功能,但他们会考虑拉取请求。

https://github.com/aspnet/EntityFrameworkCore/issues/4050

解决方法

在没有 IndexAttribute 的情况下向 Code First 模型添加索引的推荐方法是使用 Entity Framework Fluent API。例如,可以将以下内容添加到您的上下文中(派生自 DbContext):

    /// <summary>
    /// Creates database structure not supported with Annotations using Fluent syntax.
    /// </summary>
    /// <param name="optionsBuilder">The configuration interface.</param>
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Story>().HasIndex(
            story => new { story.Date, story.Published }).IsUnique(false);
    }

这为 Story.Date 和 Story.Published 创建了一个非唯一的两列索引。在此更改之后,使用:

dotnet ef migrations add <name>
dotnet ef database update

值得注意的是生成了什么样的迁移代码来创建这个索引(你可以直接使用它来自定义你的迁移来创建索引而不是将代码添加到你的上下文class):

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.CreateTable(
        name: "Stories",
        columns: table => new
        {
            Id = table.Column<int>(nullable: false)
                .Annotation("Autoincrement", true),
            Author = table.Column<string>(maxLength: 64, nullable: true),
            Date = table.Column<DateTime>(nullable: false),
            Published = table.Column<bool>(nullable: false),
            Title = table.Column<string>(nullable: true)
        },
        constraints: table =>
        {
            table.PrimaryKey("PK_Stories", x => x.Id);
        });

    migrationBuilder.CreateIndex(
        name: "IX_Stories_Date_Published",
        table: "Stories",
        columns: new[] { "Date", "Published" });
}

这些劳动的成果:

自从您提出问题后,这似乎有所改变。 jsakamoto 已实现 NuGet 包,允许您保留 [Index] 属性。唯一的区别是变量的顺序;您不能再将 Order=0 作为最后一个变量,而是:

[Index("IX_TreeFiddy", 0, IsUnique = false)]
public string LochNessMonster { get; set; }

[Index("IX_TreeFiddy", 1, IsUnique = false)]
public int CentsGiven { get; set; }

覆盖 OnModelCreating()

// Override "OnModelCreating"
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    // .. and invoke "BuildIndexesFromAnnotations"!
    modelBuilder.BuildIndexesFromAnnotations();
}

这里是link:IndexAttribute for .NET Core NuGet package