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 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.
public static ObservableCollection<TEntity> Local<TEntity>(this DbSet<TEntity> set)
where TEntity : class
{
var context = set.GetService<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.
Can you share the code that you are using to register the context in services?
@rowanmiller this is a desktop WPF application. I forgot to mention that. DbContext looks like the following:
public abstract class DbContextBase : DbContext
{
public DbContextBase()
: base()
{ }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
...
}
}
Ah, got you - I thought the GetService call was to a DI container in ASP.NET Core 😄. Could you share a complete code listing that shows the error, it's a little hard to picture how things are all interacting with the snippets provided.
@rowanmiller Here it is the relevant code, if you need more info let me know. The exception occurs in the method LoadUsers(), when invoking the extention method Local() Thanks
public class UserViewModel
{
public UserViewModel()
{
this.DbContext = new ModuleDbContext ();
...
}
private ModuleDbContext DbContext { get; private set; }
private ObservableCollection<User> Users { get; private set; }
private void LoadUsers()
{
DbContext.Users
.OrderBy(u => u.LoginId)
.Load();
...
Users = DbContext.Users.Local(); //Exception invoking Local() extension method
}
public override void OnNavigatedTo(NavigationContext navigationContext)
{
LoadUsers();
}
}
The extention method looks like the following:
public static class EntityFramework7Extentions
{
public static ObservableCollection<TEntity> Local<TEntity>(this DbSet<TEntity> set)
where TEntity : class
{
var context = set.GetService<DbContext>();
var data = context.ChangeTracker.Entries<TEntity>().Select(e => e.Entity);
var collection = new ObservableCollection<TEntity>(data);
collection.CollectionChanged += (s, e) =>
{
if (e.NewItems != null)
{
context.AddRange(e.NewItems.Cast<TEntity>());
}
if (e.OldItems != null)
{
context.RemoveRange(e.OldItems.Cast<TEntity>());
}
};
return collection;
}
}
Finally the DbContext definition:
public class DbContextBase : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
var connStringBuilder = new SqlConnectionStringBuilder();
connStringBuilder.UserID = "MyUser";
...
builder.UseSqlServer(connStringBuilder.ConnectionString);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
...
}
}
public class ModuleDbContext : DbContextBase {
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
...
}
public DbSet<User> Users { get; set; }
}
@ajcvickers is it intended to be able to resolve the context from the service provider?
A simplified repro without any base classes etc.
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
using (var db = new ModuleDbContext())
{
var context = db.Users.GetService<DbContext>();
}
}
}
public class ModuleDbContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
builder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Test;Trusted_Connection=True;");
}
public DbSet<User> Users { get; set; }
}
public class User
{
public int UserId { get; set; }
public string Name { get; set; }
}
}
Unhandled Exception: System.InvalidOperationException: 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<TContext> object in its constructor and passes it to the base constructor for DbContext.
at Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure`1 accessor)
at ConsoleApplication1.Program.Main(String[] args) in c:\users\rowmil\documents\visual studio 2015\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs:line 12
@rowanmiller AddDbContext is currently the only place where we register the DbContext directly in D.I., and then only by the type of your context, which is usually not the base DbContext type.
We do have an internal service, ICurrentDbContext, that can be used to get the current context that is being used. This is explicitly not registered as DbContext because of issues with scoping when people use AddDbContext with a non-derived context type. We could do a TryAdd for DbContext that would delegate to this service--I think that would work, but I would want to do some testing before committing to it.
For now, the workaround is this:
var context = db.Users.GetService<ICurrentDbContext>().Context;
The workaround works fine for us. We have replaced DbContext type for ICurrentDbContext for the moment. Thanks
I have a similar problem. Using DI in my startup and setting conn string in OnConfiguring.
InvalidOperationException: 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
Here's some snippets:
StartUp
services.AddScoped< IUnitOfWork, UnitOfWork >();
services.AddScoped< IDbContext, LeaseContext >();
services.AddTransient(typeof(IRepository< >), typeof(Repository<>));
services.AddTransient< IPersonService, PersonService >();
services.AddTransient< IAccountService, AccountService >();
services.AddTransient< IContractService, ContractService >();
services.AddTransient< IEntityService, EntityService >();
services.AddTransient< IFinanceService, FinanceService >();
services.AddTransient< ILocationService, LocationService >();
services.AddTransient< IPropertyService, PropertyService >();
services.AddTransient< ISystemService, SystemService >();
services.AddTransient< ITenantDocumentService, TenantDocumentService >();
services.AddSingleton(typeof(IConfigurationRoot), Configuration);
DbContext
public class LeaseContext : DbContext, IDbContext
{
private readonly IConfigurationRoot _config;
public LeaseContext(IConfigurationRoot config)
{
_config = config;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var conn = _config["Data:DefaultConnection:ConnectionString"];
optionsBuilder.UseSqlServer(conn);
base.OnConfiguring(optionsBuilder);
}
public new DbSet< T > Set< T >() where T : class
{
return base.Set< T >();
}
public int Commit()
{
return base.SaveChanges();
}
}
Note for triage: I would have expected context.GetService<DbContext>(); to have thrown because DbContext is not registered in the container, but it still throws the " No database provider has been configured" exception.
@takazm - your issue looks different from the one being discussed here, please open a new issue. If you can include a complete project that reproduces the issue that would be good as I don't see anything obviously wrong in your code.
@rowanmiller The reasoning is this:
- The GetService extension method on the context is intended for resolving EF services, usually those scoped to a context instance. I have never seen it used for random services unrelated to EF.
- If it is used for random services unrelated to EF, then it will work if those services have been registered. This works if done right, but the error message doesn't address it if done wrong, but this doesn't seem super important--it would be very much an advanced scenario.
- The only way we can guess that a provider is not registered is when a service is requested but has not been registered.
- It is reasonable to assume that the missing service is not a core service because it would be hard to get to this point at all if core services were not registered.
- Therefore, the vast majority of the time the reason a service is missing is because the provider wasn't registered, and this is in fact a common error, so we try to give the most direct and succinct guidance possible.
All of that logic still holds in this case except that the app was expecting DbContext to be registered. DbContext isn't some random service, it's still a core service. And we used to register it, so before RC2 the code was using the API exactly as intended. If we put it back, as I suggested, then it would again work as the app expected. So I don't think we should change the error message, but if we want to be completely correct we could add some additional wording indicating the the reason we think the provider wasn't registered was because a service was not found.
I was under the impression that using '. AddDnContext()' is optional. My DbContext is mapped to an interface IDbContext which i registered. my vode executes instantiates the context but throws the exception when the query results is supposed to materialize
we could add some additional wording indicating the reason we think the provider wasn't registered was because a service was not found.
I think that would be good. If the GetService() extension method on the context is only supposed to be used for EF services another option would be to check for a marker interface that all EF services would need to implement, but that seems overkill :smile:
Opened https://github.com/aspnet/EntityFramework/issues/5500 to improve the exception message as it is really not helpful when you are trying to manually resolve something that is not registered. Discussed and agreed that ICurrentDbContext is fine for the moment and we don't need to start registereing the current context as a DbContext service in the internal service provider.
Noting that in EF 3, the ICurrentDbContext is now in Microsoft.EntityFrameworkCore.Infrastructure instead of Microsoft.EntityFrameworkCore.Internal.
Is the workaround unchanged in EF 3 but using the Infrastructure namespace instead of the Internal namespace?
@sjb-sjb You should not be running into this kind of problem with EF Core 3. Please open a new issue and attach a small, runnable project or post a complete, runnable code listing that demonstrates the behavior you are seeing.