0

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?}");
            });
        }
    }

enter image description here enter image description here enter image description here

eusataf
  • 807
  • 1
  • 12
  • 24

1 Answers1

3
SqlException Cannot open database "BookStore" requested by the login. The login failed. Login failed for user 'HOME-PC\Root'.

You are trying to connect to your SQL Server with user HOME-PC\Root, But this account is not allowed to use database BookStore.

This may caused by two reasons:

  • Either: HOME-PC\Root is not a login (in sys.server_principals)

  • Or: HOME-PC\Root is set up but not mapped to a user in the database
    test (sys.database_principals)

I'd go for the 2nd option: the error message implies the default database is either not there or no rights in it, rather than not set up as a login.

To test if it's set up as a login

SELECT SUSER_ID('HOME-PC\Root') -- (**not** SUSER_SID)

If NULL

CREATE LOGIN [HOME-PC\Root] FROM WINDOWS

If not NULL

USE test
GO
SELECT USER_ID('HOME-PC\Root')

If NULL

USE test
GO
CREATE USER [HOME-PC\Root] FROM LOGIN [HOME-PC\Root]

This answer refer to issue, You can follow this link to check more details.

Or you can try to follow these steps:

  1. Go to SQL Server >> Security >> Logins and right click on NT AUTHORITY\NETWORK SERVICE and select Properties
  2. In newly opened screen of Login Properties, go to the “User Mapping” tab. Then, on the “User Mapping” tab, select the desired database – especially the database for which this error message is displayed. On the lower screen, check the role db_owner. Click OK.
Xinran Shen
  • 8,416
  • 2
  • 3
  • 12