c# - 如何在迁移中使用 DbContext?

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

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

感谢您的帮助!

最佳答案

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

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 方法中,并很好地注释它们。

关于c# - 如何在迁移中使用 DbContext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46011243/

相关文章:

c# - 如何使用 C# 取消删除文件?

c# - 如何设置 NUnit 来运行我的项目的单元测试?

c# - 从对象更新 EF

c# - 每个 RIA 查询都会创建不同的 EF 对象上下文吗?

c# - 在 Owin 自托管应用程序中使用授权服务文件

c# - 使用手动设置凭据时,EWS 自动发现停止工作

c# - Visual Studio 将 "case variable:"之后的代码标记为不可访问

c# - 我应该使用 MySQL Connector/ODBC 还是 System.Data.Odbc?

.net - 需要 JavaScript 代码方面的帮助

c# - ASP.NET Web 窗体和 MySql Entity Framework : "Nested transactions are not supported"