【问题标题】:How use DbContext in migration?如何在迁移中使用 DbContext?
【发布时间】:2017-09-02 06:45:17
【问题描述】:

我如何使用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)
        {
        }
    }
}

感谢您的帮助!

【问题讨论】:

    标签: c# .net entity-framework migration entity-framework-migrations


    【解决方案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
        }
    }
    

    请记住,如果您不想迁移多个 POCO,请不要将它们添加到您的 OnModelCreating 方法中,并对其进行注释。

    【讨论】:

    • 这适用于 EF Core 3.0 吗?无法弄清楚如何实现它。
    猜你喜欢
    • 1970-01-01
    • 2015-05-20
    • 2020-06-21
    • 1970-01-01
    • 2013-10-20
    • 2015-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多