更新数据库而不在实体框架中迁移

Ful*_*ack 5 c# asp.net entity-framework

我在 Visual Studio 中创建了一个 ASP.NET MVC 示例应用程序。我添加了两个类,如下所示:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Price { get; set; }
    public ICollection<Product> Products { get; set; }
}

public class Order
{
    public int Id{ get; set; }
    public Product Product { get; set; }
    public int ProductId { get; set; }
    public DateTime RegisterDate { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后我DbSet在 main 中添加了两个DbContext,如下所示:

 public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public IDbSet<Product> Products { get; set; }
    public IDbSet<Order> Orders { get; set; }

    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}
Run Code Online (Sandbox Code Playgroud)

但现在当我运行项目时,我收到此错误:

自创建数据库以来,支持“ApplicationDbContext”上下文的模型已更改

Add-migrations我只是想知道有没有一种方法可以在不使用迁移(和)的情况下更新数据库update-database

bub*_*ubi 6

您可以按照您想要的方式更新数据库结构(查询、通过 DBMS 用户界面等)。
如果这样做,您需要禁用配置检查。

Database.SetInitializer<YourContext>(null);
Run Code Online (Sandbox Code Playgroud)

(我将其插入上下文中的静态构造函数中)


ash*_*hin 4

您可以启用自动迁移来实现此目的。这种方法肯定使用代码优先迁移,但您不需要使用Add-Migration命令或update-database

\n\n

首先从包管理器控制台运行Enable-Migrations \xe2\x80\x93EnableAutomaticMigrations以生成 Configuration 类,如下所示:

\n\n
internal sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext>\n{\n  public Configuration()\n  {\n    AutomaticMigrationsEnabled = true;\n  }\n\n  protected override void Seed(ApplicationDbContext context)\n  { \n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

现在您可以更新数据库上下文的构造函数以迁移到最新版本,如下所示:

\n\n
public ApplicationDbContext()\n    : base("DefaultConnection", throwIfV1Schema: false)\n{\n   Database.SetInitializer(\n             new MigrateDatabaseToLatestVersion<ApplicationDbContext, Configuration>());\n   this.Database.Initialize(true);\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

或者在应用程序启动时迁移到最新版本,如下所示:

\n\n
using (var context = new ApplicationDbContext())\n {\n    Database.SetInitializer(\n              new MigrateDatabaseToLatestVersion<ApplicationDbContext, Configuration>());\n    context.Database.Initialize(true);\n }\n
Run Code Online (Sandbox Code Playgroud)\n\n

更新

\n\n

如果您根本不想使用迁移,您可以考虑将数据库初始值设定项设置为 null 并使用脚本手动处理数据库迁移

\n\n
Database.SetInitializer<YourContext>(null);\n
Run Code Online (Sandbox Code Playgroud)\n