ASP.NET Core with Entity Framework Core error, Login Failed


I was working with the EF NuGet package Microsoft.EntityFramework.Tools.DotNet and executed the command-line interface (CLI), also shown in Figure 1.

dotnet ef database drop

Running this method resulted in the same behavior:

context.Database.EnsureDeleted();

clip_image002

Figure 1, Entity Framework Core, CLI

I am not sure what exactly I was thinking, but it I did not really expect it to drop my entire database, even though the message was pretty clear in Figure 1.  For some reason I thought it was only going to remove the tables.  I likely got this impression because of what the context.Database.EnsureCreated() method does in my Initializer when my ASP.NET Core application starts… Nonetheless, when I then tried to update the database using this command, see Figure 2 in addition,

dotnet ef database update

What I realize now is that the when I am pointing to a local database and run context.Database.EnsureDeleted(), it drops the database, but when I then run context.Database.EnsureCreated() it creates it again, but the same is not so when you are pointing to an AZure SQL database.

image

Figure 2, cannot login to Entity Framework Core database hosted on Azure SQL via an ASP.NET Core Web Application, Login Failed

OK, fair is fair that I could not login, but perhaps stating the database does not exist at all would have moved me forward a bit faster.  SO, if you get this and nothing has changed, maybe your database got deleted….be sure to take a back up from time to time and check out this link here for more about managing EF migrations.

When I was developing my application and when it was pointed to the local database, when I ran the context.Database.EnsureCreated() it created a database, however when I was pointing to an Azure SQL instance, the database was not created.

context.Database.EnsureCreated()

Initially, I was logging in to the Azure portal and manually recreating the database each time I needed to update the database, until I found that I can run the following DOTNET command which recreates the database, there may be a better way, but this is what I found so far, maybe there is a CREATEDB command which I have not yet discovered, see Figure 3.

dotnet ef database update

image

Figure 3, don’t drop the database if you do then just use ef to recover, but the data is gone

The error I received is shown in Figure 4, and the output is below it in text format so you can check if the exception stack I got matches yours…

clip_image002[5]

Figure 4, SqlException: Login failed for user ‘’, Entity Framework Core, SQL Azure

An error occurred while starting the application.
SqlException: Login failed for user 'HealthFit'.
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, object providerInfo, bool redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, bool applyTransientFaultHandling)
•	SqlException: Login failed for user 'HealthFit'.
o	System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, object providerInfo, bool redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, bool applyTransientFaultHandling)
o	System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
o	System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
o	System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
o	System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
o	System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, uint waitForMultipleObjectsTimeout, bool allowCreate, bool onlyOneCheckConnection, DbConnectionOptions userOptions, out DbConnectionInternal connection)
o	System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions, out DbConnectionInternal connection)
o	System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, out DbConnectionInternal connection)
o	System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions)
o	System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource<DbConnectionInternal> retry)
o	System.Data.SqlClient.SqlConnection.Open()
o	Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open()
o	Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerDatabaseCreator+<>c__DisplayClass11_0.<Exists>b__0(DateTime giveUp)
o	Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute<TState, TResult>(Func<TState, TResult> operation, Func<TState, ExecutionResult<TResult>> verifySucceeded, TState state)
o	Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute<TState, TResult>(IExecutionStrategy strategy, Func<TState, TResult> operation, TState state)
o	Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator.EnsureDeleted()
o	HealthAndFitness.Data.DbInitializer.Initialize(HealthAndFitnessContext context) in DbInitializer.cs
+ 
10.	    public class DbInitializer
11.	    {
12.	        public static void Initialize(HealthAndFitnessContext context)
13.	        {
14.	            //context.Database.EnsureCreatedAsync();
15.	            //context.Database.EnsureCreated();
16.	            context.Database.EnsureDeleted(); return;
17.	
18.	            if (context.Athletes.Any())
19.	            {
20.	                //database has been seeded
21.	                return;
22.	            }
o	HealthAndFitness.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, HealthAndFitnessContext context) in Startup.cs
+ 
62.	            {
63.	                routes.MapRoute(
64.	                    name: "default",
65.	                    template: "{controller=Home}/{action=Index}/{id?}");
66.	            });
67.	
68.	            DbInitializer.Initialize(context);
69.	        }
70.	    }
71.	}
o	System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
o	Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
o	Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
•	



•	System.Data.SqlClient.SqlException: Login failed for user 'HealthFit'.
•	   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling)
•	   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
•	   at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
•	   at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
•	   at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
•	   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
•	   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
•	   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
•	   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
•	   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
•	   at System.Data.SqlClient.SqlConnection.Open()
•	   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open()
•	   at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerDatabaseCreator.<>c__DisplayClass11_0.<Exists>b__0(DateTime giveUp)
•	   at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](Func`2 operation, Func`2 verifySucceeded, TState state)
•	   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, Func`2 operation, TState state)
•	   at Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator.EnsureDeleted()
•	   at HealthAndFitness.Data.DbInitializer.Initialize(HealthAndFitnessContext context) in C:\Users\benperk\Source\Repos\EasyAuth\HealthAndFitness\HealthAndFitness\Data\DbInitializer.cs:line 16
•	   at HealthAndFitness.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, HealthAndFitnessContext context) in C:\Users\benperk\Source\Repos\EasyAuth\HealthAndFitness\HealthAndFitness\Startup.cs:line 68
•	--- End of stack trace from previous location where exception was thrown ---
•	   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
•	   at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
•	   at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
•	ClientConnectionId:5909d5d2-8ee0-43b7-9cea-079ac043394b
Error Number:18456,State:1,Class:14


Comments (2)

  1. Mojtaba says:

    step1: Make sure you have full access to the database. permissions in database is very important for every transaction in your database.
    step2: You write dispose method in class entity framework.
    step3: Create login in your database and these write into Connection String in iis.
    Best regards.

  2. John Henckel says:

    Thanks!! this really helped me. I am migrating from EF 6 to EF Core, and the latter does not automatically create the db for you, so this error message was very confusing.

Skip to main content