[英]How to create database in another location instead of default lactation c:\Users\USER in ASP.NET Core 2.2
I want to create database in a folder in my project, but by default the database is created in C:\\Users\\USER.我想在我的项目的文件夹中创建数据库,但默认情况下,数据库是在 C:\\Users\\USER 中创建的。
This is my appsetting.json :这是我的 appsetting.json :
"ConnectionStrings": {
"MvcMusicStoreContext":
"Server=(localdb)\\mssqllocaldb;Database=MvcMusicStoreContext;Trusted_Connection=True;MultipleActiveResultSets=true"
}
How to change database location to another folder in my computer.如何将数据库位置更改为我计算机中的另一个文件夹。 I use asp.net core 2.2 in Visual Studio 2017
我在 Visual Studio 2017 中使用 asp.net core 2.2
i change ConnectionStrings with AttachDBFileName:我用 AttachDBFileName 更改 ConnectionStrings:
"ConnectionStrings": {
"MvcMusicStoreContext":
//"Server=(localdb)\\mssqllocaldb;Database=MvcMusicStoreContext;Trusted_Connection=True;MultipleActiveResultSets=true"
"Server=(localdb)\\MSSQLLocalDB;AttachDBFilename=[DataDirectory]\\App_Data\\MvcMusicStoreContext.mdf;Trusted_Connection=True;MultipleActiveResultSets=true"
}
and in ConfigureServices in startup:并在启动时的 ConfigureServices 中:
string path = Directory.GetCurrentDirectory();
services.AddDbContext<MvcMusicStoreContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MvcMusicStoreContext")
.Replace("[DataDirectory]",path)));
Unfortunately, the above solution did not work in VS2019 (16.8.4) in my Razor project (Core 3.1):不幸的是,上述解决方案在我的 Razor 项目(Core 3.1)中的 VS2019(16.8.4)中不起作用:
An attempt to attach an auto-named database for file C:\WebApplication1\App_Data\WebApp1db.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
The solution was to add Initial Catalog=MyNotAutoNamedDb;
解决方案是添加
Initial Catalog=MyNotAutoNamedDb;
to appsetting.json
project file.到
appsetting.json
项目文件。 Before that, you should also create the App_Data
directory specified in the path.在此之前,您还应该创建路径中指定的
App_Data
目录。
appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;AttachDBFilename=[DataDirectory]\\App_Data\\WebApp1db.mdf;Initial Catalog=MyNotAutoNamedDb;Trusted_Connection=True;MultipleActiveResultSets=true"
}
Startup.cs
string path = Directory.GetCurrentDirectory();
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")
.Replace("[DataDirectory]", path)));
Please also don't forget to add using System.IO;
也请不要忘记使用
System.IO;
添加System.IO;
to your Startup.cs
file.到您的
Startup.cs
文件。 I tested the solution creating model, adding migration and updating database using EF, works without problems with the database file in the project structure.我测试了解决方案创建模型,使用 EF 添加迁移和更新数据库,项目结构中的数据库文件没有问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.