Why can't my generic Blazor app read the LocalDb for Identity?

Rod Falanga 666 Reputation points
2025-01-04T21:28:57.7166667+00:00

I wanted to see how a new Blazor Web app uses the LocalDb that is created when you create a new application that uses Individual Accounts during the project creation process. In my AppSettings.json file it created this connection string:

"ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-BlazorWebWithIdentity-5435ed71-e6f7-4a07-bf75-3acd150ee815;Trusted_Connection=True;MultipleActiveResultSets=true"
  }

Then later in the Program.cs file I put in this:

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString, sqlOptions =>
    {
        sqlOptions.EnableRetryOnFailure(
            maxRetryCount: 5,
            maxRetryDelay: TimeSpan.FromSeconds(30),
            errorNumbersToAdd: null);
    }));

However, when I debug the app, I get this error when I try to create a login:

at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.ExecuteImplementationAsyncTState,TResult ClientConnectionId:62785e65-5c0f-4c3e-a8b3-63523fca0e45 Error Number:4060,State:1,Class:11 --- End of inner exception stack trace --- at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.ExecuteImplementationAsyncTState,TResult at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.ExecuteAsyncTState,TResult at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync() Exception thrown: 'Microsoft.EntityFrameworkCore.Storage.RetryLimitExceededException' in System.Private.CoreLib.dll An exception of type 'Microsoft.EntityFrameworkCore.Storage.RetryLimitExceededException' occurred in System.Private.CoreLib.dll but was not handled in user code The maximum number of retries (5) was exceeded while executing database operations with 'SqlServerRetryingExecutionStrategy'. See the inner exception for the most recent failure.

I'm using .NET 9

Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | .NET | Blazor
{count} votes

Accepted answer
  1. Jack Dang (WICLOUD CORPORATION) 1,020 Reputation points Microsoft External Staff
    2025-07-28T07:47:36.0966667+00:00

    Hi @Rod Falanga , Thanks for reaching out. The error you're encountering, specifically the RetryLimitExceededException with an inner Error Number: 4060, indicates that your Blazor application is unable to connect to the LocalDB instance, likely because the database cannot be accessed or doesn't exist. Here are some steps to troubleshoot and resolve this issue:

    1. Verify LocalDB Installation: Ensure that SQL Server LocalDB is installed on your machine. Since you're using Visual Studio, LocalDB is typically included, but it’s worth confirming. You can check this by opening SQL Server Object Explorer in Visual Studio or running sqllocaldb info in a command prompt to see if (localdb)\mssqllocaldb is available. If LocalDB is not installed, you can install SQL Server Express, which includes LocalDB, from the official Microsoft website.
    2. Check Database Existence: The connection string in your appsettings.json references a specific database (aspnet-BlazorWebWithIdentity-...). This database is not automatically created when you set up a Blazor app with Individual Accounts. You need to initialize it by running Entity Framework Core migrations. Open the Package Manager Console in Visual Studio and execute the command Update-Database. This will create the database and apply the necessary Identity schema.
    3. Validate Connection String: Double-check the connection string in appsettings.json. Ensure the server name (localdb)\mssqllocaldb is correct and that Trusted_Connection=True is appropriate for your environment. If you're running the app on a different machine or environment, you may need to adjust the server name or authentication settings.
    4. Test Database Connectivity: Use SQL Server Management Studio (SSMS) or Visual Studio’s SQL Server Object Explorer to connect to (localdb)\mssqllocaldb. This can help confirm whether the LocalDB instance is running and accessible. If you encounter connection issues, ensure the LocalDB service is started by running sqllocaldb start mssqllocaldb in a command prompt.
    5. Review EF Core Configuration: In your Program.cs, the AddDbContext configuration looks correct, but ensure that the ApplicationDbContext class is properly set up to use the Identity framework. Verify that it inherits from IdentityDbContext (or a similar base class) and that no additional configurations are interfering with the database connection.
    6. Inspect Inner Exception Details: The error mentions an inner exception. Check the full stack trace or enable detailed logging to get more context about the failure. You can enable EF Core logging by adding .EnableSensitiveDataLogging() to your DbContext options in Program.cs (temporarily, for debugging purposes).
    7. Ensure Migrations Are Applied: If you’ve made changes to your ApplicationDbContext or Identity models, ensure that migrations are up to date. Run Add-Migration followed by Update-Database in the Package Manager Console to apply any pending changes.

    Hope this helps!

    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Anonymous
    2025-01-06T03:05:06.51+00:00

    If this is the first time for you to create a local database to test Identity, you might need to make sure that database has been created. If you didn't do anything to create the database, you might take a look at this section, I mean you might run Update-Database in Package Manager Console window

    Here's my test result, I create a new .net 9 blazor web app auto-rendered mode, and after I run the app the try to register a user, I got error message below, which indicating that I'm not able to connect to the database, but the truth is that I haven't created this database yet. But since we didn't see the inner exception you shared, I'm not sure whether we are facing the same issue.

    User's image

    If you do face the same issue as mine, if you press F5 to continue the app, you might see screenshot below which suggestion you to run update database command.

    User's image


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Tiny


  2. AgaveJoe 30,206 Reputation points
    2025-01-10T13:53:18.7966667+00:00

    since the database is one that is included as a part of the Visual Studio project template, to create Identity tables (when I chose Individual Accounts) I don't know what more it is that I have to do, in order to create the database.

    As far as I can tell and after several recommendations you finally ran update-database in the Program Manager Console. You did not report any errors after executing update-database so I'm guessing the Identity database was created.

    Reference documentation

    https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-9.0&tabs=visual-studio

    Is there something that I need to install? And if so, what?

    The Visual Studio installs a development version of SQL Server; (localdb)\mssqllocaldb. You should not have to install anything, other than Visual Studio, to work with data. Have you tried connecting to the database using the tooling in Visual Studio (SQL Server Object Explorer) as suggested above? You can also use SQL management studio.

    At this point, you should be able to register an account in your application. Have you tried running the Blazor application and registering?

    If you are still having problems and want help then we, the community, need the steps you are performing and any error messages you encounter along the way. That will help us help you.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.