Changing location of database .mdf file from default in c:\users\username (2)

Dean Everhart 1,541 Reputation points
2022-12-02T14:16:19.937+00:00

Objective: move the database (.(mdf) from original location to within the project folder on an introductory Core 6 tutorial (i.e. a very small project with no security concerns)


Location of Database Moved

Original Default Location:

Database (.mdf) created in default location at C:\Users\UserName

Moved to:

C:\Users\UserName\Desktop\SolutionName\SolutionName\ProjectName\Data


Connection String

Connection string changed from first which created the database (commented out) to the second.

  "ConnectionStrings": {  

//"ProjectNameContext": "Server=(localdb)\\mssqllocaldb;Database=ProjectName;Trusted_Connection=True;MultipleActiveResultSets=true"  

**"ProjectNameContext": "Server=(localdb)\\mssqllocaldb;AttachDbFilename=[DataDirectory]\\Data\\ProjectName.mdf;Trusted_Connection=True;MultipleActiveResultSets=true"**  

using Microsoft.EntityFrameworkCore;  
using Microsoft.Extensions.DependencyInjection;  
using ProjectName.Data;  
var builder = WebApplication.CreateBuilder(args);  
builder.Services.AddDbContext<ProjectNameContext>(options =>  
    options.UseSqlServer(builder.Configuration.GetConnectionString("ProjectNameContext") ?? throw new InvalidOperationException("Connection string 'ProjectNameContext' not found.")));  

// _______________________________________________________  

string path = Directory.GetCurrentDirectory();  
var connectionString = builder.Configuration.GetConnectionString("ProjectNameContext").Replace("[DataDirectory]", path);  

// _______________________________________________________  

// Add services to the container.  
builder.Services.AddControllersWithViews();  

var app = builder.Build();  

// Configure the HTTP request pipeline.  
if (!app.Environment.IsDevelopment())  
{  
    app.UseExceptionHandler("/Home/Error");  
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.  
    app.UseHsts();  
}  

app.UseHttpsRedirection();  
app.UseStaticFiles();  

app.UseRouting();  

app.UseAuthorization();  

app.MapControllerRoute(  
    name: "default",  
    pattern: "{controller=Home}/{action=Index}/{id?}");  

app.Run();  

Entity Framework Migration

Result

using Microsoft.EntityFrameworkCore.Migrations;  

#nullable disable  

namespace ProjectName.Migrations  
{  
    /// <inheritdoc />  
    public partial class ChangeDbLocation01 : Migration  
    {  
        /// <inheritdoc />  
        protected override void Up(MigrationBuilder migrationBuilder)  
        {  

        }  

        /// <inheritdoc />  
        protected override void Down(MigrationBuilder migrationBuilder)  
        {  

        }  
    }  
}  

Error

An unhandled exception occurred while processing the request.
SqlException: An attempt to attach an auto-named database for file [DataDirectory]\Data\ProjectName.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, bool callerHasConnectionLock, bool asyncClose)
ProjectName.Controllers.Class01NameController.Index() in Class01NameController.cs

  1. return View(await _context.Class01Name.ToListAsync());
  2. _context = context;
  3. }
    1. // GET: Class01Name
  4. public async Task<IActionResult> Index()
  5. {
  6. return View(await _context.Class01Name.ToListAsync());
  7. }
    1. // GET: Class01Name/Details/5
  8. public async Task<IActionResult> Details(int? id)
  9. {
  10. if (id == null || _context.Class01Name == null)
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,816 questions
{count} votes

Accepted answer
  1. Anonymous
    2022-12-05T02:18:12.037+00:00

    Hi @Dean Everhart ,

    266916-image.png

    The issue relates the above code, from your code, we can see you are using the incorrect connection string. So, try to modify your code as below:

     var builder = WebApplication.CreateBuilder(args);  
      
     string path = Directory.GetCurrentDirectory();  
     var connectionString = builder.Configuration.GetConnectionString("ProjectNameContext").Replace("[DataDirectory]", path);  
      
     builder.Services.AddDbContext<ProjectNameContext>(options =>  
         options.UseSqlServer(connectionString));      
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments

0 additional answers

Sort by: Most helpful

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.