Code First Migration尝试重新创建enitre db而不是更新更改

时间:2015-05-17 12:45:46

标签: asp.net-mvc ef-code-first ef-migrations

我首先尝试使用代码启用迁移,但我遇到了一些问题。 我在mvc5网站上工作,我有一个数据层的dll,域名类的dll,然后是网站本身。 我已经运行了网站,所有表格都已创建。现在我更改了其中一个域类的单个属性的名称,并希望更新数据库。但它试图再次创造一切! 我更改了属性,在控制台中输入add-migration,然后创建了迁移文件,但是它包含了我所有类的CreateTable,而不仅仅是对那个表/类的更改。 我已经使用控制台来启用迁移,因此应该按顺序进行。它在我的网站项目中创建了Migration文件夹和Configuration.cs文件。

以下是我的代码的外观:

    internal sealed class Configuration :DbMigrationsConfiguration<Playground.Web.Models.ApplicationDbContext>
    {
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = false;
    }

    protected override void Seed(Playground.Web.Models.ApplicationDbContext context)
    {
        //  This method will be called after migrating to the latest version.

        //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
        //  to avoid creating duplicate seed data. E.g.
        //
        //    context.People.AddOrUpdate(
        //      p => p.FullName,
        //      new Person { FullName = "Andrew Peters" },
        //      new Person { FullName = "Brice Lambson" },
        //      new Person { FullName = "Rowan Miller" }
        //    );
        //
    }
}

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("PlaygroundContext", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

1 个答案:

答案 0 :(得分:0)

首次配置迁移时,需要添加基线迁移。如果您有现有表,则需要告知EF进行无操作迁移:

Add-Migration InitialCreate –IgnoreChanges

现在,未来的迁移将基于基线进行增量。 https://msdn.microsoft.com/en-us/data/dn579398.aspx#option1