【问题标题】:Entity Framework Core database migration in C#C# 中的 Entity Framework Core 数据库迁移
【发布时间】:2021-01-11 22:34:23
【问题描述】:

我正在尝试通过启动 ASP.NET Core 3.1 Web 应用程序来迁移数据库(数据库已预先创建)。我通过在 Visual Studio 包管理器控制台中启用迁移来创建迁移:

enable-migrations

然后创建了一个迁移:

Add-Migration TestTable –Context MyDbContext 

TestTable 创建一个简单的表,我用它来测试迁移。

我希望能够在启动时迁移数据库,无需使用 Visual Studio 包管理器控制台,也无需使用update-database 命令。

我试过这个:

var migrationAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
services.AddDbContext<MyDbContext>(options => 
    options.UseSqlServer(
        Configuration.GetConnectionString("MyConnectionString"),
        sql => sql.MigrationAssembly(migrationAssembly))));

我没有收到任何错误,但表永远不会被创建。我在表上尝试了简单的 crud 操作,但由于表不存在而引发错误,我还检查了 SQL Server 对象资源管理器,但表不存在。

任何想法将不胜感激。

最好的

【问题讨论】:

    标签: c# entity-framework-core


    【解决方案1】:

    看看这段代码

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DataContext dataContext)
    {
        // migrate any database changes on startup (includes initial db creation)
        dataContext.Database.Migrate();
    
        ...
     }
    

    这是参考链接: https://jasonwatmore.com/post/2019/12/27/aspnet-core-automatic-ef-core-migrations-to-sql-database-on-startup

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-09
      • 2017-05-16
      • 2011-01-12
      • 1970-01-01
      • 2019-02-12
      • 2017-10-27
      • 1970-01-01
      • 2018-11-05
      相关资源
      最近更新 更多