Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

There was an error running the selected code generator: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOption

I am using Visual Studio 2022 Preview and .NET 6 SDK.

Here I am creating a webAPI project with 2 layers. api project (Bgvsystem.webAPI) class library (BgvSystem.Persistance)

NuGet packages-

Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 6.0.0-rc.1.21452.10

Install-Package Microsoft.EntityFrameworkCore.Tools -Version 6.0.0-rc.1.21452.10

Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design -Version 6.0.0-rc.1.21464.1

When I try to add a controller using scaffolding, I get the below error

There was an error running the selected code generator: unable to resolve service for type 'microsoft.entityframeworkcore.dbcontextoption.. While attempting to activate Dbcontext in  .net 6 and visual studio 2022 preview

enter image description here

How to resolve this? Please help with this.

like image 883
GOPAL SHARMA Avatar asked Dec 28 '25 15:12

GOPAL SHARMA


2 Answers

You can create a dbcontext factory class in same folder with your ApplicationDbContext class. This factory class creates ApplicationDbContext at design time and scaffolding runs correctly.

Source: https://github.com/dotnet/Scaffolding/issues/1765

public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
    public ApplicationDbContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
        optionsBuilder.UseSqlServer("Server=(localdb)\\MSSQLLocalDB;Database=EcommerceDb;Trusted_Connection=True;MultipleActiveResultSets=true");
    
        return new ApplicationDbContext(optionsBuilder.Options);
    }
}
like image 177
Simant Avatar answered Dec 31 '25 17:12

Simant


You can create a dbcontext factory class in same folder with your ApplicationDbContext class. This factory class creates ApplicationDbContext at design time and scaffolding runs correctly.

public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
        public ApplicationDbContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
            optionsBuilder.UseSqlServer("Server=YourServer; Database=YourDb; Integrated Security=true; MultipleActiveResultSets=true; Trusted_Connection=True");

            return new ApplicationDbContext(optionsBuilder.Options);
        }
}
like image 23
mahdi hoseinpoor Avatar answered Dec 31 '25 18:12

mahdi hoseinpoor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!