Unable Scaffold To Razor view

111 views Asked by At

Unable to resolve service for type 'Microsoft EntityFrameworkCore DbContextOptions`1[DonnaPerfum DataAccess Data ApplicationDbContext] while attempting to activate DonnaPerfum DataAccess Data ApplicationDbContext.

i have this error when i wanna scaffold to razor views.
ScreenShots

<a href="https://i.stack.imgur.com/7WAJM.jpg">AddController</a>  
<a href="https://i.stack.imgur.com/7AovK.jpg">SettingUp</a>  
<a href="https://i.stack.imgur.com/fEzHZ.jpg">ErrorView</a>

var builder = WebApplication.CreateBuilder(args);
    
// Add services to the container.
var connectionString =   builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddMvc();
builder.Services.AddDbContext<ApplicationDbContext>(options =>          options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
            
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddDefaultIdentity<IdentityUser>(options=> options.SignIn.RequireConfirmedAccount = true).AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();
builder.Services.AddControllers();
builder.Services.AddControllersWithViews();
            
builder.Services.AddRazorPages().AddRazorRuntimeCompilation();
var app = builder.Build();

[--applicationDbContext--]

using Donna.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
    
    
namespace DonnaPerfum.DataAccess.Data
{
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options):base(options)
{
}
public DbSet<Category> Categories { get; set; }
}
}
1

There are 1 answers

4
Chen On

There are two ways you can try it:

1.Put the connection string in ApplicationDbContext as below

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
         if (!optionsBuilder.IsConfigured)
         {
             optionsBuilder.UseSqlServer("Your connection string");
          }
    }

2.Tell the tools how to create your DbContext by implementing the Microsoft.EntityFrameworkCore.Design.IDesignTimeDbContextFactory interface

public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
    {
        public ApplicationDbContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
            optionsBuilder.UseSqlServer("Your connection string");

            return new ApplicationDbContext(optionsBuilder.Options);
        }
    }

Using both methods I can also successfully add scaffolding.