首页 > 解决方案 > EF 6.3:它为从 DataAnnotation 更改为 FluentAPI 创建了相同的迁移

问题描述

我有数据注释:

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

现在我们需要把它移到 Fluent API(不要问我为什么)。我的代码:

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

它生成以下迁移:

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

正如我们所看到的,它的作用相同,并且在 Up 和 Down 中具有相同的代码。但它为什么会产生呢?

标签: c#entity-frameworkdata-annotationsentity-framework-migrationsef-fluent-api

解决方案


您已从Index字段中删除数据注释,这就是为什么您DropIndex(...)在方法中生成行Up()和方法中的相应CreateIndex(...)行的原因Down()。同时,您已经通过 Fluent API 添加了索引,它为您提供了其余部分(CreateIndex(...)Up()方法中和DropIndex(...)在 中Down())。

因此,EF 检测到模型中的两个更改,并且不检查 Fluent API 是否生成与删除的数据注释完全相同的索引。


推荐阅读