简体   繁体   English

ASP.NET Core Entity Framework Core 找不到 IndexAttribute

[英]ASP.NET Core Entity Framework Core cannot find IndexAttribute

I receive the following from Visual Studio Code on my Mac, both in IDE and console window after executing "dotnet run":在执行“dotnet run”后,我从 Mac 上的 Visual Studio Code 收到以下内容,包括 IDE 和控制台 window:

The type or namespace name 'IndexAttribute' could not be found找不到类型或命名空间名称“IndexAttribute”

I have a class called Story which I want to use for generating a database with Code First.我有一个名为 Story 的 class,我想用它来使用 Code First 生成数据库。 This class has a primary key marked with KeyAttribute and Author string marked with MaxLengthAttribute, so both of those work (using System.ComponentModel.DataAnnotations).这个 class 有一个用 KeyAttribute 标记的主键和用 MaxLengthAttribute 标记的作者字符串,所以这两个都有效(使用 System.ComponentModel.DataAnnotations)。 Two more fields, DateTime Date and bool IsPublished, have IndexAttribute applied (it's a two-column index).另外两个字段 DateTime Date 和 bool IsPublished 应用了 IndexAttribute(它是一个两列索引)。 I explicitly named it IX_DatePublished, IsUnique = false, and use Order = 1 for the Date field and Order = 2 for the IsPublished field.我明确将其命名为 IX_DatePublished,IsUnique = false,并为 Date 字段使用 Order = 1,为 IsPublished 字段使用 Order = 2。

  • What do I put in project.json before running "dotnet restore" to have it pull in the right stuff for IndexAttribute to work?在运行“dotnet restore”之前,我应该在 project.json 中放入什么,让它为 IndexAttribute 工作引入正确的东西?
  • Does EF included with ASPCore1 for Mac/Linux not have the right namespace included?包含在 Mac/Linux 的 ASPCore1 中的 EF 是否没有包含正确的命名空间?

Thank you!谢谢!

I am still in the process of getting familiar with Core tools; 我仍然在熟悉核心工具; further research revealed that this feature is not supported but they would consider a pull request. 进一步的研究表明,不支持此功能,但他们会考虑拉取请求。

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

The work-around 解决方法

The recommended way to add indexes to Code First models in the absence of IndexAttribute is to use Entity Framework Fluent API. 在没有IndexAttribute的情况下向Code First模型添加索引的推荐方法是使用Entity Framework Fluent API。 For example the following could be added to your context (derived from DbContext): 例如,可以将以下内容添加到您的上下文(从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);
    }

This creates a two-column index for Story.Date and Story.Published that's not unique. 这为Story.Date和Story.Published创建了一个双列索引,它不是唯一的。 Following this change, use: 完成此更改后,请使用:

dotnet ef migrations add <name>
dotnet ef database update

It's interesting to note what kind of Migration code is generated to create this index (you could use this directly to customize your migrations to create index instead of adding code to your Context class): 有趣的是要注意生成哪种迁移代码来创建此索引(您可以直接使用它来自定义迁移以创建索引而不是向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" });
}

The fruit of such labors: 这些劳动的成果:

SQLiteStudio显示生成的表

This seems to have changed since you asked the question. 自从您提出问题以来,这似乎已经发生了变化。 jsakamoto has implemented NuGet package that allows you to keep your [Index] attribute. jsakamoto已经实现了NuGet包,允许您保留[Index]属性。 The only difference is order of variables; 唯一的区别是变量的顺序; you can no longer have Order=0 as your last variable but rather do: 你不能再将Order=0作为你的最后一个变量,而是做:

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

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

Override OnModelCreating() 覆盖OnModelCreating()

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

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

Here is link to: IndexAttribute for .NET Core NuGet package 以下是指向.NET Core NuGet包的IndexAttribute的链接

This is now supported natively with EF Core 5.0 and the standard namespace:现在,EF Core 5.0 和标准命名空间原生支持此功能:

using Microsoft.EntityFrameworkCore;

You define the index via attribute at the class level:您通过 class 级别的属性定义索引:

[Index(nameof(Date), nameof(Published), IsUnique = false)]
public class Story
{
    public int Id { get; set; }
    public DateTime Date { get; set; }
    public bool Published { get; set; }
}

You can specify one column for the index, or multiple as shown above to create a composite key.您可以为索引指定一列,也可以如上所示指定多列来创建复合键。 More info here .更多信息在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM