I am working on an ASP.NET Core 7.0 MVC app. I have created a data access layer using EF Core 7.0 with a database-first approach. I was trying to create a Razor view through the "AddView" option from the controller for the "Create" process.
However, I am getting this error:
This is how I inject my DbContext
:
builder.Services.AddDbContext<NorthwindContext>(options => options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")));
I am new to ASP.NET Core. It looks like I have to pass additional options in the Program.cs
file. I did a Google search, but couldn't find any help!
If I create the view manually it might work. However, I would like to create it through the scaffolding process.
This is my NorthwindContext
code:
After removing the parameterless constructor as per Neil I am getting the new error:
CodePudding user response:
More specifically to my comment, the AddDbContext registers the context class in the asp.net core DI container so it can be provided whenever any class or process wants an instance of the DbContext.
The view generator will want that. However, if the DI container find a parameterless constructor it will use that first, and therefore not use the constructor that passes in the options.
The outcome is a context is provided that does not have the "UseSqlServer" options set.
Hence the error that a database provider has not been configured.
Remove that parameterless constructor from the DbContext and you should be good to go.
CodePudding user response:
The latest error indicates the constructor requires an object of type DbContextOptions.But the injector cannot create the instance.
You could try with the parameterless constructor and configure the options in OnConfiguring method
And the picture you've shown indicates you've seprated Modes from your MVC projects,Make sure you've setted the right startup project(right click on your solution -- Set startup projects) and configrue which projects would contain the migration classes
public class SomeDbContext : DbContext
{
public SomeDbContext()
{
}
public DbSet<SomeEntity> SomeEntity { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("connectionstring", b => b.MigrationsAssembly("MVCProj"));
}
}
Regist it as below:
services.AddDbContext<SomeDbContext>();
If you still got the error,please upload the minimal codes that could reproduce the error