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?.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With