Asp.net Core Entity Framework cannot find IndexAttribute

后端 未结 2 1524
醉话见心
醉话见心 2021-02-05 12:32

I receive the following from Visual Studio Code on my Mac, both in IDE and console window after executing \"dotnet run\":

The type or namespace name \'IndexAttribute\' c

2条回答
  •  自闭症患者
    2021-02-05 12:56

    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

    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. For example the following could be added to your context (derived from DbContext):

        /// 
        /// Creates database structure not supported with Annotations using Fluent syntax.
        /// 
        /// The configuration interface.
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity().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. Following this change, use:

    dotnet ef migrations add 
    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):

    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "Stories",
            columns: table => new
            {
                Id = table.Column(nullable: false)
                    .Annotation("Autoincrement", true),
                Author = table.Column(maxLength: 64, nullable: true),
                Date = table.Column(nullable: false),
                Published = table.Column(nullable: false),
                Title = table.Column(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:

提交回复
热议问题