I'm trying to connect the ms sql localdb mdf database.
Microsoft.Entity Framework Core.SqlServer" Version="5.0.17".
I get an error:
" SqlException Cannot open database "BookStore" requested by the login. The login failed.
Login failed for user 'HOME-PC\Root'."
Question.
How to connect ms sql localdb mdf database?
The question considers the project Project-1 (not working).
Created a project Project-2 (working).
I registered the connection string in Startup.cs.
Result: The database is being connected.
Project-2 (working)
Startup.cs. (Code snippet)
public class Startup
{
public static string Mdf_Directory
{
get
{
var directoryPath = AppDomain.CurrentDomain.BaseDirectory;
var fullPath = Path.GetFullPath(Path.Combine(directoryPath, "..//..//..//DB"));
return fullPath; }
}
public string astootConnectionString = "Data Source=(LocalDB)\\MSSQLLocalDB; " +
"AttachDbFilename=" + Mdf_Directory + "\\BookStore.mdf;" +
" Integrated Security=True; Connect Timeout=30;";
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
string path = Mdf_Directory; // для теста
services.AddDbContext<ApplicationContext>(options =>
options.UseSqlServer(astootConnectionString));
services.AddMvc();
}
Project-1 (not working)
Book.cs
using System;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;
namespace ASPNET5EFWebApp1.Models
{
public class Book
{
[Key]
public int book_id { get; set; }
public string title { get; set; }
public string isbn13 { get; set; }
public int language_id { get; set; }
public DateTime publication_date { get; set; }
public int publisher_id { get; set; }
}
}
DBContextBookStore.cs
using Microsoft.EntityFrameworkCore;
namespace ASPNET5EFWebApp1.Models
{
public class DBContextBookStore : DbContext
{
public DbSet<Book> Books { get; set; }
// public DBContextBookStore(DbContextOptions<DBContextBookStore> options)
public DBContextBookStore(DbContextOptions options)
: base(options)
{
// Database.EnsureCreated(); // создаем базу данных при первом обращении
}
}
}
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=BookStore;Trusted_Connection=True;"
}
}
HomeController.cs
public class HomeController : Controller
{
private readonly ILogger _logger;
private DBContextBookStore db;
public HomeController(ILogger<HomeController> logger, DBContextBookStore context)
{
_logger = logger;
db = context;
}
public async Task<IActionResult> Index()
{
var dfdf = await db.Books.ToListAsync();
return View();
}
}
Project-2 (working)
Startup.cs (Full code)
public class Startup
{
public static string Mdf_Directory
{
get
{
var directoryPath = AppDomain.CurrentDomain.BaseDirectory;
var fullPath = Path.GetFullPath(Path.Combine(directoryPath, "..//..//..//DB"));
return fullPath; }
}
public string astootConnectionString = "Data Source=(LocalDB)\\MSSQLLocalDB; " +
"AttachDbFilename=" + Mdf_Directory + "\\BookStore.mdf;" +
" Integrated Security=True; Connect Timeout=30;";
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
string path = Mdf_Directory; // для теста
services.AddDbContext<ApplicationContext>(options =>
options.UseSqlServer(astootConnectionString));
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}


