Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Core RC2 FinaI Issue: No database provider has been configured for this DbContext

After replacing EF Core rc 1 with EF Core rc 2 final, We are getting an invalid operation exception when calling GetService() method bellow. The goal here is to get the corresponding DbContext from any given DbSet:

public static ObservableCollection<TEntity> Local<TEntity>(this DbSet<TEntity> set)
            where TEntity : class
{
            var context = set.GetService<DbContext>();
            ...
}

The exception full message:

No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.

We effectively are setting the database provider in OnConfiguring:

protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
    base.OnConfiguring(builder);
    var connStringBuilder = new SqlConnectionStringBuilder();
    connStringBuilder.UserID = "MyUserID";
    ...         
    builder.UseSqlServer(connStringBuilder.ConnectionString);
}

So it seems that the issue comes from the method GetService() not resolving the correct DbContext instance for the given DbSet?.

like image 861
E-Bat Avatar asked Oct 19 '22 09:10

E-Bat


1 Answers

After reporting this issue with the EF team, they bring the following workaround:

public static ObservableCollection<TEntity> Local<TEntity>(this DbSet<TEntity> set)
            where TEntity : class
{
    var context = set.GetService<ICurrentDbContext>().Context;            
    ...
}

Note the use of the interface ICurrentDbContext instead of DbContext.

Details here

like image 186
E-Bat Avatar answered Oct 30 '22 23:10

E-Bat