How use DbContext in migration?

别说谁变了你拦得住时间么 提交于 2020-06-27 18:30:27

问题


How can I use DbContext which works with the current database (that now use in migration).

Example:

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

Thanks for help!


回答1:


Create a class for your migration configuration :

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

Then reference this to your DbContext Class:

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

Remember if you do not want to migrate several POCOs then do not add them within your OnModelCreating Method and well comment them.



来源:https://stackoverflow.com/questions/46011243/how-use-dbcontext-in-migration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!