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

问题描述 投票:0回答:10

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

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

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

“尝试激活“LibraryData.LibraryContext”时无法解析类型“Microsoft.entityFrameworkCore.DbContextOptions”1[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; }
    }

启动.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?}");
            });
        }

程序.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; }
    }
c# .net asp.net-core dbcontext
10个回答
30
投票

我通过向 EF Core CLI 工具指定 --project--startup-project 选项修复了此错误,如下所示:

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

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

--startup-project 表示哪个项目包含数据库连接信息和其他信息。


10
投票

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

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

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

public LibraryContext()
{
}

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


4
投票

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

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


3
投票

您应该添加一段代码来告诉工具应如何创建 DBContext。当类库项目中有 DBContext 引用到 Web 项目时,就需要它。

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

        return new BloggingContext(optionsBuilder.Options);
    }
}

3
投票

只需为 DbContext 添加空构造函数即可解决您的问题

public partial class TPPSSDbContext : DbContext
{
    public TPPSSDbContext() { } //this one
    public TPPSSDbContext(DbContextOptions<TPPSSDbContext> options) 
        : base(options) 
    { 
    }
}

2
投票

尝试修改你的上下文:

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

        }

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

参考此文档:

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


1
投票

在 Visual Studio 2022 中使用“New Scaffolded Item...”出现此错误。就像 @Huggster 和 @Aytsemik 指出的解决方案是使用

IDesignTimeDbContextFactory
。如果您使用 SQL Server 以及
appsettings.json
中的连接字符串,这是一个完整的示例:

internal class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
    ApplicationDbContext IDesignTimeDbContextFactory<ApplicationDbContext>.CreateDbContext(string[] args)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();

        var builder = new DbContextOptionsBuilder<ApplicationDbContext>();
        var connectionString = configuration.GetConnectionString("DefaultConnection");

        builder.UseSqlServer(connectionString);

        return new ApplicationDbContext(builder.Options);
    }
}

如果安装在单独的类库中,请记住安装 NuGet

Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Json
,以便
ConfigurationBuilder
SetBasePath
正常工作。

来源:

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

https://stackoverflow.com/a/52418717/3850405

https://stackoverflow.com/a/38170147/3850405


0
投票

此外,您必须定义一个空的构造函数。如下;

public ApplicationDbContext() {
    // for scaffolding
}

0
投票

在为这个问题寻找了两个小时的时间后,我找到了解决办法。结果发现我有 Entityframework 8.0.0,我不得不降级到 7.0.9。那时它就像一个魅力。希望有帮助。


0
投票

就我而言,当我尝试注册自定义工作单元服务时遇到了这个问题。这是我解决的方法:

builder.Services.AddDbContext<KioskAdminDbContext>(options => options.UseSqlServer(CnStr)); // usual db context registration
builder.Services.AddScoped<DbContext, KioskAdminDbContext>(); // this is what I added

builder.Services.AddScoped<IUnitOfWork, UnitOfWork>(); // my custom service
© www.soinside.com 2019 - 2024. All rights reserved.