如何在 ASP.NET Core 2.2 中的另一个位置创建数据库而不是默认的哺乳 c:\Users\USER

How to create database in another location instead of default lactation c:\Users\USER in ASP.NET Core 2.2

我想在项目的文件夹中创建数据库,但默认情况下数据库是在 C:\Users\USER.

中创建的

这是我的 appsetting.json :

"ConnectionStrings": {
    "MvcMusicStoreContext": 
      "Server=(localdb)\mssqllocaldb;Database=MvcMusicStoreContext;Trusted_Connection=True;MultipleActiveResultSets=true"

  }

如何将数据库位置更改为我计算机中的另一个文件夹。我在 Visual Studio 2017

中使用 asp.net 核心 2.2

我用 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"

  }

并在启动时的 ConfigureServices 中:

string path = Directory.GetCurrentDirectory(); 

  services.AddDbContext<MvcMusicStoreContext>(options =>
                  options.UseSqlServer(Configuration.GetConnectionString("MvcMusicStoreContext")
                  .Replace("[DataDirectory]",path)));

不幸的是,上述解决方案在我的 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.

解决方案是将 Initial Catalog=MyNotAutoNamedDb; 添加到 appsetting.json 项目文件。在此之前,您还应该创建路径中指定的 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)));

也请不要忘记将 using System.IO; 添加到您的 Startup.cs 文件中。 我测试了创建模型的解决方案,使用 EF 添加迁移和更新数据库,项目结构中的数据库文件没有问题。