简体   繁体   中英

Automatic Migration and manual invocation of Update-Database

Do I have to manually issue the Update-Database command in the package manager console even though I have automatic migrations turned on?

I'm running MVC4 and EF6. The solution is targeted for .NET 4 (I can't change this unfortunately).

EDIT : I'm aware of the difference between Code Migrations that would require me to properly seed existing tables. This question is more based towards a scenario where I add a table that has no relations, which I would think would just run?

EDIT 2 : Table that should be added automatically

============

New Table definition

public class InboundFile : Entity
{
    [Required]
    public String FilePath { get; set; }
}

EF Config file

    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = true;
        MigrationsDirectory = @"Migrations";
    }

    protected override void Seed(Unifi.Context.DBContext context)
    {
        context.InboundFiles.AddOrUpdate(
            x => x.FilePath,
            new InboundFile { CreateDate = DateTime.Now, ModifiedDate = DateTime.Now, FilePath = "c:/test", IsDeleted = false }
        );
    }

DB Context

public class DBContext : DbContext {

    public DBContext()
        : base("MyConn")
    {

    }

    public DbSet<User> Users { get; set; }

    public DbSet<UserRole> UserRoles { get; set; }

    public DbSet<Region> Regions { get; set; }

    public DbSet<InboundFile> InboundFiles { get; set; }

}

Try placing this in your Application_Start

Database.SetInitializer(new MigrateDatabaseToLatestVersion<DbContext, Configuration>);
using (var temp = new DbContext()) {
    temp.Database.Initialize(true);
}

This will force it to run update-database , and in doing so seed , every time your application starts.

Update-Database triggers an " update " operation. You can run your app and database will be updated on app start.

I prefer to run Update-Database manually because I can see if there are any db migration errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM