2017-09-02 102 views
0

如何使用DbContext与当前数据库(现在用于迁移)一起使用。如何在迁移中使用DbContext?

例子:

namespace Data.SqlServer.Migrations 
{ 
    [DbContext(typeof(MyDbContext))]  // I want use this context 
    [Migration("CustomMigration_DataSeed")] 
    public partial class DataSeedMigration : Migration 
    { 
     protected override void Up(MigrationBuilder migrationBuilder) 
     { 
      // add some entities 
      _context.User.Add(new User()); 
     } 

     protected override void Down(MigrationBuilder migrationBuilder) 
     { 
     } 
    } 
} 

感谢您的帮助!

回答

1

为迁移配置创建一个类:

internal sealed class Configuration : DbMigrationsConfiguration<MyDbContext> 
{ 
    public Configuration() 
    { 
     AutomaticMigrationsEnabled = true; 
     //On true you might be losing data be aware. 
     AutomaticMigrationDataLossAllowed = false; 
     ContextKey = "Path To Your DbContext"; 
    } 

    protected override void Seed(MyDbContext 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" } 
     // ); 
     // 
    } 
} 

然后引用了此信息的DbContext类:

public class MyDbContext : DbContext 
{ 
    public MyDbContext() 
     : base("name=MyConnection") 
    { 
     Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDbContext,Configuration>("MyConnection")); 
    } 

    protected override void OnModelCreating(ModelBuilder modelBuilder) 
    { 
     //here you can MAP Your Models/Entities 
    } 
} 

记住,如果你不希望迁移几个波苏斯那么不中添加他们你的OnModelCreating方法,并评论他们。

相关问题