skip to Main Content

I am encountering errors while attempting to run an Entity Framework (EF) update command (dotnet ef database update) from my ASP.NET Core application. The application is connected to a database hosted on Azure. After executing the EF update command, I am receiving two different errors:

  1. An exception has been raised that is likely due to a transient failure. Consider enabling transient error resiliency by adding 'EnableRetryOnFailure' to the 'UseSqlServer' call.

  2. A DefaultAzureCredential error indicating failure to retrieve a token from the included credentials, despite attempting troubleshooting steps re-authenticating my Azure account in Visual Studio Code. see the error (This account '***' needs re-authentication. Please go to Tools->Options->Azure Services Authentication, and re-authenticate the account you want to use..

    - Stored credentials not found. Need to authenticate user in VSCode Azure Account. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/vscodecredential/troubleshoot

    - Azure CLI not installed

    - PowerShell is not installed.)

I re-configured my SQL call to use the EnableRetryOnFailure method to enable transient error resiliency expecting this to be resolved but it didn’t fix it. Then followed the troubleshooting guide provided for the DefaultAzureCredential error,re-authenticating my Azure account in Visual Studio Code and unfortunately this didn’t sort it too.

I have tested it against a local database and I am still getting same errors !

Additionally, the Azure CLI is already installed so not too sure why it’s saying it’s not !

Any guidance or assistance in resolving this issue would be greatly appreciated. Thank you.

2

Answers


  1. Chosen as BEST ANSWER

    An update - as my current IDE is vs code, in order to re-authenticate I was singing out - then signing in using Azure Account extension but apparently this wasn't storing the credentials correctly in vs code to validate them in Azure SQL. I had to try this via VS by going to Tools -> options -> Azure Services Authentication - I signed in from there, then the EF core command worked subsequently !


  2. Transient failures in Entity Framework can occur due to various reasons, including network issues, temporary unavailability of the database server, timeouts, or resource contention. These failures are often intermittent and temporary, hence the term transient.

    Implement retry logic using the EnableRetryOnFailure method to automatically retry failed database operations.
    Implement proper error handling to catch transient failure exceptions and retry database operations as needed.
    Monitor and diagnose network and database server issues to address underlying causes of transient failures.

    Re-authenticate your Azure account in Visual Studio Code as prompted.
    Clear any cached credentials and ensure necessary permissions are granted for Azure services.

    I created an ASP .NET Core 8 application with an Azure database by following the steps below in Visual Studio Code.

    I have added the required packages to the project as mentioned below.

    dotnet add package Microsoft.EntityFrameworkCore
    dotnet add package Microsoft.EntityFrameworkCore.SqlServer
    dotnet add package Microsoft.EntityFrameworkCore.Tools
    dotnet add package Microsoft.EntityFrameworkCore.Design
    dotnet add package Microsoft.VisualStudio.Web.CodeGeneration
    

    MyMvcApp.csproj:

    <Project Sdk="Microsoft.NET.Sdk.Web">
      <PropertyGroup>
        <TargetFramework>net8.0</TargetFramework>
        <Nullable>enable</Nullable>
        <ImplicitUsings>enable</ImplicitUsings>
      </PropertyGroup>
      <ItemGroup>
        <PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.4" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.4">
          <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
          <PrivateAssets>all</PrivateAssets>
        </PackageReference>
        <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.4" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.4">
          <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
          <PrivateAssets>all</PrivateAssets>
        </PackageReference>
        <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration" Version="8.0.2" />
      </ItemGroup>
    </Project>
    

    I added the following code to my Program.cs file.

    builder.Services.AddDbContext<Studentdbcontext>(options  =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("StudentConnection")));
    

    This is My Complete Program.cs:

    using Microsoft.EntityFrameworkCore;
    using MyMvcApp.Models;
    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddControllersWithViews();
    builder.Services.AddDbContext<Studentdbcontext>(options =>
                  options.UseSqlServer(builder.Configuration.GetConnectionString("StudentConnection")));
    var app = builder.Build();
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthorization();
    app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    app.Run();
    

    Ensure that your ConnectionString is correct.

    appsettings.json

      "AllowedHosts": "*",
     "ConnectionStrings": {
       "StudentConnection": "Server=tcp:<AzureServerName>.database.windows.net,1433;Initial Catalog=<AzureDataBAseName>;Persist Security Info=False;User ID=<UserName>;Password=<Password>;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
     }}
    

    Below is my model class and DbContext class. I generate the controller and views code using the following command:

    dotnet aspnet-codegenerator controller -name <ControllerName> -m <ModelClassName> -dc <DbContextName> --relativeFolderPath Controllers --useDefaultLayout
    

    Students:

    namespace MyMvcApp.Models
    {
        public class Students
        {
            public int Id { get; set; } 
            public string? Name { get; set; }
        }
    }
    

    Studentdbcontext:

    using Microsoft.EntityFrameworkCore;
    namespace MyMvcApp.Models
    {
        public class Studentdbcontext:DbContext
        {
            public Studentdbcontext(DbContextOptions<Studentdbcontext> options)
               : base(options)
            {
            }
            public DbSet<Students> students { get; set; }
        }
    }
    

    I installed the dotnet-ef using this command:

    dotnet tool install --global dotnet-ef
    

    as shown below.

    enter image description here

    After creating an SQL Server and database in the Azure Portal, add your current IP address to the firewall rules of networking in SQL Server, as shown below.

    enter image description here

    I successfully enabled the migrations and updated the database, as shown below.

    dotnet ef migrations add initalmigrations 
    dotnet ef database update  
    

    enter image description here

    Output:

    enter image description here

    enter image description here

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search