我无法在使用 SQLite 数据库的 ASP.NET Core Web 应用程序的发布版本上应用 ApplicationDbContext 的现有迁移。结果,我必须将我的 sqlite .db 文件从 Debug 构建(我能够应用迁移)复制到 Release 构建,以便我可以将它部署在我的 Ubuntu 服务器上。要么,要么我必须调用app.UseDatabaseErrorPage();
在 public void Configure()
内部方法Startup.cs
生产环境,不推荐。
要重现此问题,请在 Visual Studio 中使用个人用户帐户身份验证创建一个 ASP.NET Core Web 应用程序 (.NET Core)。我调用我的项目海文 .
然后,更新 project.json
使用 SQLite 而不是 SQL Server。
// Change from this
"Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
"Microsoft.EntityFrameworkCore.SqlServer.Design": {
"version": "1.0.1",
"type": "build"
},
// to this
"Microsoft.EntityFrameworkCore.Sqlite": "1.0.1",
"Microsoft.EntityFrameworkCore.Sqlite.Design": {
"version": "1.0.1",
"type": "build"
},
然后,更新
Startup.cs
使用 SQLite 而不是 SQL Server:// Change from this
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
// to this
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
然后,打开
appsettings.json
并更改 DefaultConnection 以使用 SQLite 数据库。 (我命名我的 Hevn.db ):// Change DefaultConnection to use SQLite database called Hevn.db
"ConnectionStrings": {
"DefaultConnection": "Data Source=./Hevn.db"
},
然后打开命令提示符并通过导航到项目并运行
dotnet ef database update
来应用迁移cd "%USERPROFILE%/Documents/Visual Studio 2015/Projects/Hevn/src/Hevn"
dotnet ef database update
dotnet run
这将创建
bin/Debug/netcoreapp1.0
文件夹,该文件夹内包含 Hevn.db
sqlite 数据库文件。当我浏览 sqlite 文件时,我可以看到已经创建了身份验证所需的表(即 AspNetUsers
表)。但是,我无法为发布版本执行此操作。我可以运行
dotnet build -c Release
在 bin/Release/netcoreapp1.0
下构建我的应用程序的发布版本.我也可以运行 dotnet run -c Release
运行我的应用程序的发布版本。运行发布版本将创建 Hevn.db
bin/Release/netcoreapp1.0
下的 sqlite 文件,但是浏览sqlite文件显示没有创建表。此时,我唯一的选择是复制
Hevn.db
文件从调试到发布版本。我也试过
dotnet ef database update -e Production
,但这仍然会创建 Hevn.db
在调试构建下。当我在应用迁移之前在 Debug模式下运行我的 ASP.NET Core Web 应用程序时,我在尝试注册/登录时收到以下屏幕。我只需单击 Apply Migrations 或运行
dotnet ef database update
使用 SQLite 应用迁移和注册/登录工作。但是当我在 Release模式下运行我的 ASP.NET Core Web 应用程序时,当我尝试注册/登录时会出现以下屏幕。我无法将迁移应用到发布版本。
是否可以在 ASP.NET Core Web 应用的发布版本上应用迁移?还是我必须求助于将数据库迁移的 sqlite 文件从 Debug 复制到 Release?
最佳答案
dotnet ef database update
是正确的命令。但是默认情况下它在调试配置下运行。 -e 更改环境(即影响 env.IsDevelopment() 之类的代码)它不会使其在 Release 下运行。 -c before database 应该这样做。请看 https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dotnet
另一种选择是根据环境使用不同的连接字符串,然后您可以使用 -e 来控制要使用的环境。
关于sqlite - 如何在使用 SQLite 的 ASP.NET Core Web 应用程序的发布版本中为 ApplicationDbContext 应用现有迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41977810/