ASP.Net Core : Cannot open localdb requested by th

2019-07-25 05:49发布

问题:

Prompt: An unhandled exception occurred while processing the request. SqlException: Cannot open database "MoviesContext-8287b737-12b5-4c1c-8bf5-6259ea1d208b" requested by the login. The login failed. Login failed for user 'D-PC\D'.

System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, object providerInfo, bool redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, bool applyTransientFaultHandling)

I had run the following commands in the command prompt in my project's catalog before(already made my model and made a my own Dbcontext): dotnet restore dotnet ef migrations add Initial dotnet ef database update

I have checked out every method on the Internet, but all of them didn't happened in the ASP.Net Core project(Visual Studio 2017). In those ways, I cannot find where to acess the SQL serve or the web.config file.

回答1:

It is necessary to check that the database is created and, if necessary, create This is done by the context.Database.EnsureCreated();

For example:

    public static void Initialize(IServiceProvider serviceProvider)
        {
            ApplicationDЬContext context = serviceProvider.GetRequiredService<ApplicationDЬContext>();
if (!context.Database.EnsureCreated())
                context.Database.Migrate();
            if (!context.Products.Any())
            {
                context.Products.AddRange(
                new Product
                {
                    Name = "Soccer Ball ",
                    Description = "FIFA-approved size and weig",
                    Category = "Soccer",
                    Price = 19.50m
                },
                new Product
                {
                    Name = "Stadium",
                    Description = " Flat - packed 35,000- seat stadium",
                    Category = "Soccer",
                    Price = 79500
                }                
                );
                context.SaveChanges();
            }


回答2:

Run the following command in the Package Manager Console to create the migration class that will prepare the database for its first use:

Add-Migration Initial

When this command has finished, you will see a Migrations folder in the Visual Studio Solution Explorer window. This is where Entity Framework Core stores its migration classes. Run the following command to create the database and run the migration commands:

Update-Database

It can take a moment for the database to be created, but once the command has completed, you can see the effect of creating and using the database by starting.