Relocating Database from default to within project folder

Dean Everhart 1,541 Reputation points
2023-04-10T16:49:30.6133333+00:00

Moving the database location from the default to within the project folder (wwwroot/Data)

Copy database files from default... C:\Users\UserName\ContosoUniversity.Data.mdf C:\Users\UserName\ContosoUniversity.Data.ldf To...

C:\Users\User1\Desktop\ContosoUniverstiy\ContosoUniverstiy\wwwroot\Data\ContosoUniversity.Data.mdf C:\Users\User1\Desktop\ContosoUniverstiy\ContosoUniverstiy\wwwroot\Data\ContosoUniversity.Data.ldf Error:
The name 'path' does not exist in the current context ContosoUniverstiy C:\Users\User1\Desktop\ContosoUniverstiy\ContosoUniverstiy\Program.cs Program.cs

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<SchoolContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("SchoolContext").Replace("[DataDirectory]", path) ?? throw new InvalidOperationException("Connection string 'SchoolContext' not found.")));

appsettings.json

  "ConnectionStrings": {
    "SchoolContext": "Server=(localdb)\\mssqllocaldb;Database=ContosoUniverstiy.Data;Trusted_Connection=True;MultipleActiveResultSets=true"


Second Attempt changed "path" to "/Data"

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<ContosoUniverstiyEmbedContext>(options =>

    options.UseSqlServer(builder.Configuration.GetConnectionString("ContosoUniverstiyEmbedContext").Replace("[DataDirectory]", "/Data/") ?? throw new InvalidOperationException("Connection string 'SchoolContext' not found.")));


**
Error:** Possible null reference argument for parameter 'source' in 'IIncludableQueryable<Enrollment, Course?> EntityFrameworkQueryableExtensions.Include<Enrollment, Course?>(IQueryable<Enrollment> source, Expression<Func<Enrollment, Course?>> navigationPropertyPath)'.

Developer technologies ASP.NET ASP.NET Core
Developer technologies ASP.NET Other
{count} votes

1 answer

Sort by: Most helpful
  1. SurferOnWww 4,631 Reputation points
    2023-04-12T01:43:36.3566667+00:00

    Try to add the AttachDbFilename to your connextion string in the appsettings.json:

    "SchoolContext": 
      "Server=(localdb)\\mssqllocaldb;AttachDbFilename=C:\\Users\\User1\\Desktop\\ContosoUniverstiy\\ContosoUniverstiy\\wwwroot\\Data\\ContosoUniversity.Data.mdf;Database=..."
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.