Asp.net核心实体框架找不到IndexAttribute

问题描述 投票:11回答:2

在执行“dotnet run”后,我在Mac上的Visual Studio Code中收到以下内容,包括IDE和控制台窗口:

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

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

  • 在运行“dotnet restore”之前我应该​​在project.json中添加什么来让它为IndexAttribute提供正确的工作?
  • ASPCore1 for Mac / Linux中包含的EF是否包含正确的命名空间?

谢谢!

c# asp.net entity-framework asp.net-core asp.net-core-1.0
2个回答
6
投票

自从您提出问题以来,这似乎已经发生了变化。 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();
}

这里是链接:IndexAttribute for .NET Core NuGet package


19
投票

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

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

有趣的是要注意生成哪种迁移代码来创建此索引(您可以直接使用它来自定义迁移以创建索引而不是向Context类添加代码):

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

这些劳动的成果:

SQLiteStudio showing the generated table

© www.soinside.com 2019 - 2024. All rights reserved.