首页 > 解决方案 > 当我尝试在 ASP.NET 中搭建脚手架时,出现错误:无法解析类型“Microsoft.EntityFrameworkCore.DbContextOptions”的服务?

问题描述

完整的错误是:

Unable to create an object of type 'UserDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728 StackTrace:
Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions' while attempting to activate 'WebApp.Data.UserDbContext'.   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_4.<FindContextTypes>b__13()

每当我尝试搭建剃刀视图时,都会收到此错误。当我构建我的应用程序或添加迁移时,我没有收到任何错误。

这些是我的 startup.cs 中的服务:

services.AddControllersWithViews();

services.AddHttpContextAccessor();

services.AddDbContext<DataDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DataDbContextConnection"), mig => mig.MigrationsAssembly("WebApp.Infra")));

services.AddDbContext<UserDbContext>(options =>
                    options.UseSqlServer(
                        Configuration.GetConnectionString("UserDbContextConnection")));

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

services.AddRazorPages();

除了使用脚手架创建新的剃须刀页面外,一切正常。起初我得到一个错误,我的项目中有多个名为 UserDbContext 的 DbContext,但是通过将 AddDbContext 服务从 IdentityHostingStartup 移动到 Startup 来解决这个问题。在我测试我是否可以脚手架之后,我得到了这个错误。

我使用身份库进行登录,用户存储在不同的数据库中。这就是为什么我的项目中有 2 个 DbContext。

这里可能是什么问题?如果您需要更多信息,请告诉我。

UserDbContext 包含:

public class UserDbContext : IdentityDbContext<ApplicationUser>
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public UserDbContext(DbContextOptions options, IHttpContextAccessor httpContextAccessor)
        : base(options)
    {
        _httpContextAccessor = httpContextAccessor;
    }  

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }      

    public DbSet<Person> Persons { get; set; }
}

标签: c#model-view-controlleridentitydbcontextscaffolding

解决方案


推荐阅读