'在尝试激活时无法解析类型 ¨Microsoft.entityFrameworkCore.DbContextOptions¨1[LibraryData.LibraryContext] 的服务

'Unable to resolve service for type ¨Microsoft.entityFrameworkCore.DbContextOptions¨1[LibraryData.LibraryContext] while attempting to activate

我 运行 遇到了一个我自己无法解决的问题,所以我正在寻求帮助。

我最近开始学习 ASP .net 核心,想建立一个图书馆,我必须有一个数据库、登录系统和管理员权限才能从网站上添加和删除书籍.

我已经创建了登录系统和数据库,现在我想在项目中添加CRUD,但是弹出这个错误

"'尝试激活时无法解析 ¨Microsoft.entityFrameworkCore.DbContextOptions¨1[LibraryData.LibraryContext] 类型的服务"LibraryData.LibraryContext"

到目前为止,这是我的代码...

LibraryData.LibraryContext.cs

public class LibraryContext : DbContext
    {
        public LibraryContext(DbContextOptions<LibraryContext> options) : base(options)
        {

        }

        public DbSet<User> Users { get; set; }
        public DbSet<Video> Videos { get; set; }
        public DbSet<BranchHours> BranchHour { get; set; }
        public DbSet<Checkout> checkouts { get; set; }
        public DbSet<CheckoutHistory> checkoutHistorys { get; set; }
        public DbSet<Holds> holds { get; set; }
        public DbSet<LibraryAsset> LibraryAssets { get; set; }
        public DbSet<Book> Books { get; set; }
        public DbSet<LibraryBranch> libraryBranches { get; set; }
        public DbSet<LibraryCard> LibraryCards { get; set; }
        public DbSet<Status> statuses { get; set; }
    }

Startup.cs

        public IConfiguration Configuration { get; }       
        
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddMvc().AddSessionStateTempDataProvider();
            services.AddDistributedMemoryCache();
            services.AddSession();
            services.AddSingleton(Configuration);
            services.AddScoped<ILibraryAsset, LibraryAssetService>();
            services.AddControllersWithViews();
            services.AddDbContext<LibraryContext>(options
                 => options.UseSqlServer(Configuration.GetConnectionString("LibraryConnection")));
            services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<LibraryContext>();
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
            services.AddScoped<DbContext, LibraryContext>();
            services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        }

               public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSession();
            app.UseRouting();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }

Program.cs

    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }

AssetIndexListingModel.cs

    public class AssetIndexListingModel
    {
        public int Id { get; set; }
        public string ImageUrl { get; set; }
        public string Title { get; set; }
        public string AuthorOrDirector { get; set; }
        public string Type { get; set; }
        public string DeweyCallNumber { get; set; }
        public string NumberOfPages { get; set; }
        public int DateOfRealease { get; set; }
        public int AgeRes { get; set; }
        public string About { get; set; }
    }

尝试修改您的上下文:

public LibraryContext(DbContextOptions<LibraryContext> options) : base(options)
        {

        }

public LibraryContext(DbContextOptions options)
: base(options)
{
}

参考这个文件:

https://github.com/dotnet/efcore/issues/15145

可能不是解决方案,但可以解决问题。为要拾取的脚手架工具添加一个 ContextFactory。这个例子只是告诉你硬编码连接字符串有点生气。

https://docs.microsoft.com/en-us/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli#from-a-design-time-factory

我自己最近 运行 遇到了这个问题,这就是我解决问题的方法。 在 Startup.cs(配置服务)

public void ConfigureServices(IServiceCollection services)
{
    //Some Code
    services.AddDbContext<LibraryContext>();
    //Some Code
} 

然后在您的 DbContext class 中将 DbContextOptions 传递给您的基础 class,然后按如下方式配置它们。

public LibraryContext()
{
}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseSqlServer("Your Connection String");
}

我通过为 EF 指定 --project--startup-project 选项修复了这个错误核心 CLI 工具 像这样:

dotnet ef database update --verbose --project CommandService.Data   --startup-project CommandService

--project 表示哪个项目包含 DbContext class

--startup-project表示哪个项目包含Db连接信息等信息。

您应该添加一个代码来说明工具应该如何创建 DBContext。当您在引用 Web 项目的 class 库项目中有 DBContext 时需要它。

public class BloggingContextFactory : IDesignTimeDbContextFactory<BloggingContext>
{
    public BloggingContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
          optionsBuilder.UseNpgsql();

        return new BloggingContext(optionsBuilder.Options);
    }
}