Search code examples
c#visual-studioasp.net-coreentity-framework-corerazor-pages

Error when trying to add a scaffolded item in Razor Pages


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:

Error Message

I've tried the following ways to solve the problem:

  1. Clearing nuget cache
  2. Reverting all package versions to 3.1.4
  3. Adding the nuget online reference (https://api.nuget.org/v3/index.json) in package sources.
  4. Re-installing Visual Studio
  5. Clearing ComponentModelCache

Now I'm just wondering if the error is due to using 3.1 framework instead of the latest 5.0.


Solution

  • 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);
        }
    }