如何在迁移中使用DbContext? [英] How use DbContext in migration?

查看:90
本文介绍了如何在迁移中使用DbContext?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

示例:

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

感谢您的帮助!

推荐答案

为您的迁移配置创建一个类:

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

然后将其引用到您的DbContext类:

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

请记住,如果您不想迁移多个POCO,请不要在OnModelCreating方法中添加它们,以及评论他们。

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

这篇关于如何在迁移中使用DbContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆