2016-07-22 56 views
6

我收到從Visual Studio代碼下面我的Mac上,無論是在IDE和執行後控制檯窗口「的dotnet運行」:Asp.net核心實體框架找不到IndexAttribute

類型或命名空間名稱「IndexAttribute」可能找不到

我有一個叫做Story的類,我想用它來用Code First生成一個數據庫。這個類有一個標有KeyAttribute和Author字符串的主鍵標記爲MaxLengthAttribute,所以這兩個工作(使用System.ComponentModel.DataAnnotations)。另外兩個字段DateTime Date和bool IsPublished應用了IndexAttribute(這是一個兩列索引)。我明確地命名爲IX_DatePublished,IsUnique = false,對於Date字段使用Order = 1,對IsPublished字段使用Order = 2。

  • 在運行「dotnet restore」之前,我在project.json中放入了什麼東西,讓它能夠爲正在使用的索引屬性工作?
  • 包含在Mac/Linux的ASPCore1中的EF沒有包含正確的命名空間嗎?

謝謝!

回答

9

我仍然在熟悉Core工具;進一步的研究表明,這個功能不被支持,但他們會考慮拉請求。

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

的變通

推薦的方法添加索引到的Code First模型在沒有IndexAttribute的是使用實體框架流利的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