首页 > 解决方案 > 启动时默认运行

问题描述

我正在处理一个测试项目,我正试图围绕迁移展开我的头脑。

我创建了一个名为AngularASPNETCore2WebApiAuth

services.AddDbContext<ApplicationDbContext>(options =>
      options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
          b => b.MigrationsAssembly("AngularASPNETCore2WebApiAuth")));

当我开始我的测试项目并出现错误时:

System.Data.SqlClient.SqlException:'无效的对象名称'AspNetUsers'。

我当时的印象是我提供了 MigrationsAssembly,因此可以在项目启动时运行迁移。

我知道我可以使用 Update-Database 命令通过命令行更新我的数据库。

但是,如果默认情况下应用程序不运行迁移,为什么我必须在启动时提供迁移程序集。如何在启动时默认运行迁移?

标签: c#.net-coreentity-framework-migrations

解决方案


设置 MigrationsAssembly 只是告诉上下文在哪里可以找到迁移程序集,您仍然需要显式运行它(很多时候您不想在每次启动应用程序时都运行迁移)。你需要打电话

myDbContext.Database.Migrate();

执行迁移。

https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/#apply-migrations-at-runtime


推荐阅读