I have been trying to add a scaffold item in ASP.NET Core, razor pages using Entity Frameword (CRUD). My current target framework is netcoreapp3.1
.
I have the following package versions:
Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.9"
Include="Microsoft.Microsoft.EntityFrameworkCore.Tools" Version="3.1.9"
Include="Microsoft.Microsoft.VisualStudio.Web.CodeGeneration.Core" Version="3.1.4"
This is the instructions I am following: https://learn.microsoft.com/en-us/aspnet/core/data/ef-rp/intro?view=aspnetcore-5.0&tabs=visual-studio#scaffold-student-pages.
However, when I try adding a scaffold item, the following error occurs:
I've tried the following ways to solve the problem:
ComponentModelCache
Now I'm just wondering if the error is due to using 3.1 framework instead of the latest 5.0.
I revisited this question as a similar issue came up.
The problem seems to be either:
A. Package version issues
Microsoft.EntityFrameworkCore.*
packages must be compatible with Microsoft.VisualStudio.Web.CodeGeneration.Design
Updating to the latest version usually solves the issue.
(latest version according to your project's .NET framework's version)
B. "Unable to resolve service for type ... DbContextOptions ..." error
This error seems to appear when the DbContext is in a separate project.
According to Microsoft's documentation, this can be resolved by implementing an IDesignTimeDbContextFactory
.
Here is my example using SqlServer:
public class ApplicationDbContextDesignTimeFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
public ApplicationDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;MultipleActiveResultSets=true");
return new ApplicationDbContext(optionsBuilder.Options);
}
}