Home > other >  EntityFramework Database.EnsureCreated() trying to create mdf in wrong path
EntityFramework Database.EnsureCreated() trying to create mdf in wrong path

Time:03-30

I'm having weird issues with method Database.EnsureCreated() of Entity Framework core. It happens on many computers with clean installations.

As you can see it tries to create the mdf file with this path

c:\Users\AdminBLTManager.mdf

While it should be:

c:\Users\Admin\BLTManager.mdf

Terminal showing errors

The code is nothing special:

class CreateInitialDataIfDbIsEmptyBgService : IHostedService
{
    private readonly ILogger _logger;
    private readonly IServiceProvider _serviceProvider;

    public CreateInitialDataIfDbIsEmptyBgService(IServiceProvider serviceProvider, ILogger<MigrateDatabaseBgService> logger)
    {
        _serviceProvider = serviceProvider;
        _logger = logger;
    }

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        using var scope = _serviceProvider.CreateScope();
        _logger.LogWarning("Ensuring database exists...");
        var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
        dbContext.Database.EnsureCreated();

        _logger.LogWarning("Ensuring initial admin user exists when db is newly created...");
    }

    public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}

this is run in ConfigureServices()

services.AddHostedService<CreateInitialDataIfDbIsEmptyBgService>();

The weird thing is this is happening only to some computers, not on my development environment.

EDIT:

Connection string:

 "ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=BLTManager;Trusted_Connection=True;MultipleActiveResultSets=true"

},

Registering the ApplicationDbContext:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();

        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
        services.AddDatabaseDeveloperPageExceptionFilter();
        services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddRoles<IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>();
  .....
}

CodePudding user response:

This looks like an old LocalDB bug we hit once. I think it was fixed sometime after the initial 2017 release. Try updating to see if it goes away.

  • Related