Updated to latest version of rc2 now i am getting this error. I know there have been some changes, so maybe i have missed something, if someone could let me know please
I have a DbContext that inherits from IdentityDbContext
On my startup.cs page, i previously had this
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(appSettings.Data.AuthConnection.ConnectionString)
.UseRowNumberForPaging());
And remove this line from my ApplicationDbContext.cs file, as it shows an error (thought maybe not needed anymore)
public ApplicationDbContext(DbContextOptions options) : base(options) { }
Now i have updated it to this
services.AddEntityFrameworkSqlServer()
.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(appSettings.Data.AuthConnection.ConnectionString, sqlServerOptions =>
{
sqlServerOptions.UseRowNumberForPaging();
}));
But now when i run my application i get the 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.
If i re-add this line to my ApplicationDbContext.cs file
public ApplicationDbContext(DbContextOptions options) : base(options) { }
then i get compiler errors. If i hover over the base
word in the above line, it says
If i hover over the options
word, i get this error
I am running into the exact same issue as of yesterday on rc2-20215 on dnx451 using the latest nightles.
I have reacted to EF changes as seen in the Identity repo here and here
And I still get the same error. as the post above.
I am just wondering how is the service container supposed to know about what Db provider is being used now?
The .AddEntityFrameworkSqlServer() flavour text reads:
You only need to use this functionality when you want Entity Framework to resolve the services it uses from an external Microsoft.Extensions.DependencyInjection.IServiceCollection. If you are not using an external Microsoft.Extensions.DependencyInjection.IServiceCollection Entity Framework will take care of creating the services it requires.
Since I am using the normal AspNetCore Service Collection I assume that this is not used in my case?
Can anyone shed some light on this please?
Shhhh... they are still asleep in Redmond!
@Lutando @Gillardo Most likely cause is that your DbContext class needs to expose a constructor that takes a DbContextOptions<YourContext>
object. If this doesn't fix it, please post your DbContext constructors, OnConfiguring override (if you have one) and code that calls AddDbContext (if you have it).
Constructors :
public MyDbContext(DbContextOptions options) : base(options)
{
}
protected MyDbContext()
{
}
and my AddDbContext into my service container
services.AddDbContext<MyDbContext>(options =>
options.UseSqlServer(connectionString));
Thing is I am doing it the same as what I see in other repos but it doesnt seem to be working. Changing one of my constructors to
public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
{
}
does not seem to fix the issue.
@Lutando Can you check whether the constructor that takes the DbContextOptions is the one being called at runtime? Also, are you using any specific D.I. container in your app?
@ajcvickers Looks like its not. The parameterless constructor is being called. Using the stock standard AspNetCore DI Container, nothing fancy there.
@Lutando Can you remove the parameterless constructor as a workaround for now? If not, try adding this after AddDbContext:
C#
serviceCollection
.AddScoped(p => new MyContext(p.GetService<DbContextOptions<MyContext>>()));
@ajcvickers what seemed to fix it for me was doing what you suggested (removing the parameterless constructor). Another thing to mention, my base DbContext had the DbContextOptions constructor but my derived DbContext did not, after adding the DbContextOptions constructor to my derived DbContext class it worked. Odd that its been working for all this time untill the latest few updates.
@Lutando so what does your dbcontext look like now please? So i can get mine working?
Basically my only change was that I added the constructor to my derived dbContext (MyDbContext) before I did not have the constructor there and it worked for me. Not sure if you also had derived contexts...
public class MyDbContext : MyBaseDbContext
{
public MyDbContext(DbContextOptions options) : base(options)
{
}
}
public class MyBaseDbContext : DbContext
{
public MyBaseDbContext(DbContextOptions options) : base(options)
{
}
}
My dbContext inherits from IdentityDbContext, but Identity3 has not yet been updated to use the new constructors so mine still broke. Thanks for showing though
Yeah your right, it appears that the project called openiddict has not released its latest build on github yet, so this is still referencing the old version
@Gillardo FYI: the new OpenIddict packages are online.
Thanks @PinpointTownes
Closing as we think this is all addressed now, feel free to re-open or comment if that is not the case.
If anyone comes here for this issue and the above solutions haven't helped you, then you may need to do the following:
In Startup.cs you may have the line:
public IConfigurationRoot Configuration { get; set; }
Simply remove the set;
like so:
public IConfigurationRoot Configuration { get; }
seems to me that the constructor
public Db(DbContextOptions options) : base(options)
{
}
is required when using
services.AddDbContext<Db>(options => options.UseSqlServer(sqlConn));
If I would not use services.AddDbContext
and just hardcode the connection like this:
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
builder.UseSqlServer("Data Source=.\\sqlexpress;Database=...");
base.OnConfiguring(builder);
}
then I would not need that constructor
@omuleanu yes, your observations are correct. That constructor is how the options set in Startup.cs are passed to the context.
@omuleanu Spot on. The options ctor was the missing piece of the puzzle!
@omuleanu When i hardcode the connection like you did, why do I get this error?
InvalidOperationException: Unable to resolve service for type 'SchoolTest.Data.ApplicationDbContext' while attempting to activate 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`4[SchoolTest.Models.ApplicationUser,Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole,SchoolTest.Data.ApplicationDbContext,System.String]'.
Here is my dbcontext:
`public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext()
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
builder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=aspnet-SchoolTest-c1ec91a9-273f-4820-98d2-d16e57ee6188;Trusted_Connection=True;MultipleActiveResultSets=true");
base.OnConfiguring(builder);
}
}`
I am having this problem when using database migrations. The project was converted from DotNetCore 1.1 to 2.0
@nflawson - Did you follow guide here properly to upgrade your application? https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/
I am using MySql, and getting the similar exception. How can I resolve this ? Please help .
@Bijayakumar1990 This is an old issue that has been closed for some time. If you are having a similar problem with the latest release, then please file a new issue including a full description of the problem and a runnable solution/project or full code listing that will allow us to reproduce what you are seeing.
Sorry for reopening this issue but I'm wondering that nobody suggests to get the DBcontext through DI?
public class MyController: Controller{
private MyApplicationDbContext _context;
public MyController(MyApplicationDbContext context){
_context = context;
}
}
Then you can use the context and it's disposed correctly. No need for constructing the context by yourself, thus no need for having a constructor without parameters. You can use AddDbContext in Startup.cs and pass the connectionString to the options like you wanted.
Following the suggestions, when I remove the parameterless constructor, I get:
No parameterless constructor defined for this object
and when I define a parameterless constructor, I get:
No database provider has been configured for this DbContext.
The context type is defined as:
public class ItemContext : DbContext
{
public ItemContext(DbContextOptions<ItemContext> options) : base(options)
{
}
public DbSet<Item> Tools { set; get; }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.ApplyConfiguration(new ToolItemEntityTypeConfiguration());
}
}
In startup class I have:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddCustomDbContext(Configuration);
var container = new ContainerBuilder();
container.Populate(services);
return new AutofacServiceProvider(container.Build());
}
In the same file I have:
public static class CustomExtensionMethods
{
public static IServiceCollection AddCustomDbContext(this IServiceCollection services, IConfiguration configuration)
{
services.AddDbContext<ItemContext>(options =>
{
options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"),
sqlServerOptionsAction: sqlOptions =>
{
sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
sqlOptions.EnableRetryOnFailure(maxRetryCount: 10, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
});
options.ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning));
});
return services;
}
}
Not sure why I get the above-mentioned errors when running:
dotnet ef migrations add InitialCreate -v
.AddScoped(p => new MyContext(p.GetService<DbContextOptions<MyContext>>()));
That's work.Thank you :)
Greetings,
I am now facing the same issue with EF 3.1.2
, IdentityDbContext
and dotnet ef migrations
IdentitiesDbContext.cs
public class IdentitiesDbContext : IdentityDbContext<TenantUser, Role, string, IdentityUserClaim<string>, UserRole, IdentityUserLogin<string>, IdentityRoleClaim<string>, IdentityUserToken<string>>
{
public IdentitiesDbContext(DbContextOptions<IdentitiesDbContext> options) : base(options) { }
public IdentitiesDbContext() { }
}
Startup.cs
private readonly IConfiguration _configuration;
public Startup(IConfiguration configuration)
{
_configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
var connectionString = _configuration.GetConnectionString("DefaultConnection");
var assemblyName = typeof(DbInitializer).GetTypeInfo().Assembly.GetName().Name;
services.AddDbContext<IdentitiesDbContext>(b => b.UseLazyLoadingProxies().UseSqlite(connectionString, o => o.MigrationsAssembly(assemblyName)));
}
When starting an application, constructor IdentitiesDbContext(DbContextOptions<IdentitiesDbContext> options)
is called. When calling dotnet ef migrations add -c IdentitiesDbContext -s src/Project/Project.csproj -p src/Project.Db/Project.Db.csproj
-o Data/Migrations/IdentitiesDb -v Initial
DbContextOptions
are not configured. (verified in OnConfiguring(DbContextOptionsBuilder options)
) and parameter less constructor is called.
Por algum motivo o CORE nao est谩 estendendo que 茅 para pegar as configura莽oes do Options ,
mesmo ele configurado na classe Startup . Desta forma voc锚 ter谩 que colocar essas configura莽玫es no seus contexto.
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("Data Source=localdb)\\MSSQLLocalDBte;MultiSubnetFailover=False");
}
}
@ondrejtomcik I had the same issue with EF 3.1.2. I have managed to fix it by changing the way of injecting one of the services, not connected directly with EF in the ConfigureServices method from this
services.AddTransient(typeof(IPlanService));
to this:
services.AddTransient(typeof(IPlanService), typeof(PlanService));
Solution that worked,
use connection from DI
just inject the database context in to the class where you are calling it, for instance if using a controller like bellow then it will work.
public class WorkflowController : Controller
{
// GET: WorkflowController
private readonly ApplicationDbContext context;
public WorkflowController(ApplicationDbContext applicationDb)
{
context = applicationDb;
}
LpoDetails lpoList = new LpoDetails
{
LPO_ITEMCOST = item.LPO_ITEMCOST,
LPO_QTY = item.LPO_QTY,
LPO_ITEMNAME = item.LPO_ITEMNAME,
LPO_PRICE = item.LPO_PRICE
};
context.LpoDetails.Add(lpoList);
context.SaveChanges();
Most helpful comment
seems to me that the constructor
is required when using
services.AddDbContext<Db>(options => options.UseSqlServer(sqlConn));
If I would not use
services.AddDbContext
and just hardcode the connection like this:then I would not need that constructor