Click here to Skip to main content
15,881,938 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to create database in a folder in my project, but by default the database is created in C:\Users\USER.

This is my 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


What I have tried:

I use asp.net core 2.2 in Visual Studio 2017
Posted
Updated 8-Dec-21 22:28pm
v2
Comments
Richard MacCutchan 11-Jan-20 5:35am    
Use a full path rather than just a filename in your connection string.
[no name] 11-Jan-20 5:59am    
Can you give me an example of how to do it?

If you are using the (localdb) designation then the file will be stored in the default location as described at Creating a Connection String and Working with SQL Server LocalDB | Microsoft Docs[^]. For other options see SQL Server Connection Strings for ASP.NET Web Applications | Microsoft Docs[^].
 
Share this answer
 
i change ConnectionStrings with AttachDBFileName:

"ConnectionStrings": {<br />
    "MvcMusicStoreContext":<br />
    "Server=(localdb)\\MSSQLLocalDB;AttachDBFilename=[DataDirectory]\\App_Data\\MvcMusicStoreContext.mdf;Trusted_Connection=True;MultipleActiveResultSets=true"<br />
  }

and in ConfigureServices in startup:

string path = Directory.GetCurrentDirectory(); <br />
<br />
  services.AddDbContext<MvcMusicStoreContext>(options =><br />
                  options.UseSqlServer(Configuration.GetConnectionString("MvcMusicStoreContext")<br />
                  .Replace("[DataDirectory]",path)));
 
Share this answer
 
v2
public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
Configuration = configuration;
string appRoot = env.ContentRootPath;
Environment.SetEnvironmentVariable("DataDirectory", Path.Combine(appRoot, "App_Data"));
}

"DefaultConnection": "Server=(localdb)\\mssqllocaldb;AttachDBFilename=%DataDirectory%\\aaa.mdf;Trusted_Connection=True;ConnectRetryCount=1",
use Environment.ExpandEnvironmentVariables 2 replace EnvironmentVariables (%DataDirectory%)
var ss = Environment.ExpandEnvironmentVariables(Configuration.GetConnectionString("DefaultConnection"));
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900