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.

8

There are 8 best solutions below

0
On BEST ANSWER

After struggling for 3 days, finally I found the mistake and fixed that.

Actually I had to put connection string in MyApp.Persistance.DbContextClass as below

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer("Data Source=DESKTOP-SV8GPJ2\\SQLEXPRESS;Initial Catalog=StarterAppDB;Persist Security Info=True;User ID=sa;Password=Admin@1234");
            }
        }

Then it worked fine.

0
On

I am using N-Tier Architecture and asp net Area, so along with your ApplicationDbContext class add another class (DataContextFactory) class with following code Good luck!

public class DataContextFactory : IDesignTimeDbContextFactory<AppDbContext>
{
    public AppDbContext CreateDbContext(string[] args)
    {
        var configuration = new ConfigurationBuilder()
         .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
         .AddJsonFile("appsettings.json")
         .Build();

        var optionsBuilder = new DbContextOptionsBuilder<AppDbContext>();
        optionsBuilder.UseSqlServer(configuration.GetConnectionString("KasicaConnection"));

        return new AppDbContext(optionsBuilder.Options);
    }
4
On

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);
    }
}
2
On

You need to add the DBContext to service collection in startup.cs file or pass as constructor BGvSystemContext class.

1
On

In case of .NET 6

Can you try like this

Program.cs

builder.Services.AddDbContext<YourDbContext>(options =>
     options.UseSqlServer("name=ConnectionStrings:DefaultConnection"));

appsettings.json

"ConnectionStrings": {
   "DefaultConnection": "Server=YourServer; Database=YourDb; Integrated Security=true; MultipleActiveResultSets=true; Trusted_Connection=True"
}

YourDbContext.cs

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
        optionsBuilder.UseSqlServer("Server=YourServer; Database=YourDb; Integrated Security=true; MultipleActiveResultSets=true; Trusted_Connection=True");
    }
}
0
On

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.

This issue occurs when we create API controller. For this issue put the below code in your program.cs.

builder.Services.AddDbContext(options => options.UseSqlServer(builder.Configuration.GetConnectionString("EmployeeContext")));

0
On

If you don't need the options builder for additional configuration you can dependency inject IConfiguration and use that to pass the connection string inside of OnConfiguring. This will solve the problem with ef code generation.

public class ApplicationDbContext : DbContext
{
    private IConfiguration _config;
    public ApplicationDbContext(IConfiguration config) 
    {
        _config = config;
    }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(_config.GetConnectionString("DefaultConnection"));
    }
}

And in startup you can use the paramaterless constructor for your db context instead of options builder

1
On

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