首页 > 解决方案 > 具有 2 个数据库的 Entity Framework Core ( aspnetboilerplate webapp )

问题描述

我正在使用Abp.ZeroCore.EntityFrameworkCore4.1.0,我正在尝试向UnoDbContext我的网络应用程序添加另一个上下文 (),如下所示:

https://aspnetboilerplate.com/Pages/Documents/Entity-Framework-Core#replacing-default-repositories

这是我的代码。

UnoDbContext.cs:

using Microsoft.EntityFrameworkCore;
using MyApp.Models;
using Abp.EntityFrameworkCore;

namespace MyApp.EntityFrameworkCore
{
    public class UnoDbContext : AbpDbContext
    {
        /* Define a DbSet for each entity of the application */
        public virtual DbSet<Anagrafica> Anagraficas { get; set; }

        public UnoDbContext(DbContextOptions<UnoDbContext> options)
            : base(options)
        {
        }
    }
}

UnoDbContextConfigurer:

using System.Data.Common;
using Microsoft.EntityFrameworkCore;

namespace MyApp.EntityFrameworkCore
{
    public static class UnoDbContextConfigurer
    {
        public static void Configure(DbContextOptionsBuilder<UnoDbContext> builder, string connectionString)
        {
            builder.UseSqlServer(connectionString);
        }

        public static void Configure(DbContextOptionsBuilder<UnoDbContext> builder, DbConnection connection)
        {
            builder.UseSqlServer(connection);
        }
    }
}

启动.cs:

using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Castle.Facilities.Logging;
using Abp.AspNetCore;
using Abp.Castle.Logging.Log4Net;
using MyApp.Authentication.JwtBearer;
using MyApp.Configuration;
using MyApp.Identity;
using MyApp.Web.Resources;
using Abp.AspNetCore.SignalR.Hubs;
using Abp.EntityFrameworkCore;
using MyApp.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace MyApp.Web.Startup
{
    public class Startup
    {
        private readonly IConfigurationRoot _appConfiguration;

        public Startup(IHostingEnvironment env)
        {
            _appConfiguration = env.GetAppConfiguration();
        }

        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            // MVC
            services.AddMvc(
                options => options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute())
            );

            IdentityRegistrar.Register(services);
            AuthConfigurer.Configure(services, _appConfiguration);

            services.AddScoped<IWebResourceManager, WebResourceManager>();

            services.AddSignalR();

            services.AddAbpDbContext<UnoDbContext>(options =>
            {
                options.DbContextOptions.UseSqlServer(options.ConnectionString);
            });

            // Configure Abp and Dependency Injection
            return services.AddAbp<MyAppWebMvcModule>(
                // Configure Log4Net logging
                options => options.IocManager.IocContainer.AddFacility<LoggingFacility>(
                    f => f.UseAbpLog4Net().WithConfig("log4net.config")
                )
            );
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            app.UseAbp(); // Initializes ABP framework.

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();
            app.UseAuthentication();
            app.UseJwtTokenMiddleware();

            app.UseSignalR(routes =>
            {
                routes.MapHub<AbpCommonHub>("/signalr");
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "defaultWithArea",
                    template: "{area}/{controller=Home}/{action=Index}/{id?}");

                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

默认上下文:

using Microsoft.EntityFrameworkCore;
using Abp.Zero.EntityFrameworkCore;
using MyApp.Authorization.Roles;
using MyApp.Authorization.Users;
using MyApp.MultiTenancy;
using MyApp.Models;

namespace MyApp.EntityFrameworkCore
{
    public class MyAppDbContext : AbpZeroDbContext<Tenant, Role, User, MyAppDbContext>
    {
        /* Define a DbSet for each entity of the application */

        public MyAppDbContext(DbContextOptions<MyAppDbContext> options)
            : base(options)
        {
        }
    }
}

现在,当我尝试在服务中使用 UnoDbContext 时,出现此错误:

处理请求时发生未处理的异常。HandlerException:无法创建组件“HealthCareCRM.EntityFrameworkCore.UnoDbContext”,因为它需要满足依赖关系。

'HealthCareCRM.EntityFrameworkCore.UnoDbContext' 正在等待以下依赖项: - 服务 'Microsoft.EntityFrameworkCore.DbContextOptions`1[[HealthCareCRM.EntityFrameworkCore.UnoDbContext, HealthCareCRM.EntityFrameworkCore, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] ]' 未注册。

Castle.MicroKernel.Handlers.DefaultHandler.AssertNotWaitingForDependency()

有人可以告诉我错误在哪里吗?

标签: c#sql-serverentity-framework-coreaspnetboilerplate

解决方案


看起来您的新 DbContext 对 ABP 无效。查看此示例 DbContext。自定义它并将其用作您的第二个 DbContext。

using Abp.Zero.EntityFrameworkCore;
using Abp.Zero.SampleApp.MultiTenancy;
using Abp.Zero.SampleApp.Roles;
using Abp.Zero.SampleApp.Users;
using Microsoft.EntityFrameworkCore;

namespace Abp.Zero.SampleApp.EntityFrameworkCore
{
    public class AppDbContext : AbpZeroDbContext<Tenant, Role, User, AppDbContext>
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) 
            : base(options)
        {

        }
    }
}

推荐阅读