Search code examples
c#entity-frameworkdata-annotationsentity-framework-migrationsef-fluent-api

EF 6.3: It creates the same migration for changing from DataAnnotation to FluentAPI


I have data annotation:

    [Required]
    [MaxLength(150)]
    [Index(IsUnique = true)]
    public string GuidName { get; set; }

Now we need to move it to Fluent API (and don't ask me why). My code:

        this.Property(c => c.GuidName).IsRequired().HasMaxLength(150);
        this.HasIndex(c => c.GuidName).IsUnique(true).IsClustered(false);

It generates the following migration:

    public override void Up()
    {
        DropIndex("dbo.Companies", new[] { "CompanyUniqueString" });
        CreateIndex("dbo.Companies", "CompanyUniqueString", unique: true);
    }

    public override void Down()
    {
        DropIndex("dbo.Companies", new[] { "CompanyUniqueString" });
        CreateIndex("dbo.Companies", "CompanyUniqueString", unique: true);
    }

as we can see, it does the same and has the same code in Up and Down. But why is it generated at all?


Solution

  • You have removed Index data annotation from the field, that's why do you have DropIndex(...) line generated in the Up() method and corresponding CreateIndex(...) line in the Down() method. At the same time, you have added index via Fluent API, it gives you the rest (CreateIndex(...) in the Up() method and DropIndex(...) in the Down()).

    So, EF detects two changes in the model and doesn't check if Fluent API produces exactly the same index as removed data annotation.