.net '尝试激活时无法解析类型为“Microsoft.entityFrameworkCore.DbContextOptions”1[库数据.库上下文]的服务

vom3gejh  于 2023-02-14  发布在  .NET
关注(0)|答案(8)|浏览(183)

我遇到了一个我自己解决不了的问题,所以我请求帮助。
我最近开始学习ASP.NET核心,并希望建立一个图书馆,我必须有一个数据库,登录系统和管理员的权力,能够添加和删除网站上的书籍。
我已经创建了登录系统和数据库,现在我想将CRUD添加到项目中,但是弹出此错误
尝试激活“库数据.库上下文”时,无法解析类型“Microsoft.entityFrameworkCore.DbContextOptions”1[库数据.库上下文]的服务
这是目前为止我的代码...
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; }
    }
t5fffqht

t5fffqht1#

我修复了此错误,方法是将**--project--startup-project选项指定给EF Core CLI工具**,如下所示:

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

--项目表示哪个项目包含DbContext
--startup-project表示哪个项目包含Db连接信息和其他信息。

tct7dpnv

tct7dpnv2#

我最近自己也遇到了这个问题,这就是我解决这个问题的方法。在StartupIdecs(配置服务)中

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

ctehm74n3#

可能不是解决方案,但修复了这个问题。添加一个ContextFactory以供脚手架工具拾取。有点疯狂的是,这个示例只是告诉您硬编码connectionstring。
https://learn.microsoft.com/en-us/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli#from-a-design-time-factory

q5lcpyga

q5lcpyga4#

您应该添加一个代码,说明工具应该如何创建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);
    }
}
vm0i2vca

vm0i2vca5#

尝试修改您的上下文:

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

        }

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

参考本文档:
https://github.com/dotnet/efcore/issues/15145

jxct1oxe

jxct1oxe6#

只需为DbContext添加空构造函数,它就会解决您的问题

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

smdnsysy7#

在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.ConfigurationMicrosoft.Extensions.Configuration.Json,以便ConfigurationBuilderSetBasePath正常工作。
资料来源:
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

h9vpoimq

h9vpoimq8#

另外,你必须定义一个空的构造函数,如下所示;

public ApplicationDbContext() {
    // for scaffolding
}

相关问题