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
- return View(await _context.Class01Name.ToListAsync());
- _context = context;
- }
-
- // GET: Class01Name
- public async Task<IActionResult> Index()
- {
- return View(await _context.Class01Name.ToListAsync());
- }
-
- // GET: Class01Name/Details/5
- public async Task<IActionResult> Details(int? id)
- {
- if (id == null || _context.Class01Name == null)