“使用带有EF 6的ASP.NET Core Console应用程序创建模型时不能使用上下文”

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

当我使用带有EF6的ASP.NET Core Console应用程序执行我的asp.net核心控制台应用程序时。我经常收到以下错误。

System.InvalidOperationException:创建模型时无法使用上下文。如果在OnModelCreating方法中使用上下文,或者同时由多个线程访问相同的上下文实例,则可能抛出此异常。请注意,DbContext和相关类的实例成员不保证是线程安全的。 [01/02/2018 10:59:16> 395c4e:INFO]在System.Data的System.Data.Entity.Internal.LazyInternalContext.InitializeContext()[01/02/2018 10:59:16> 395c4e:INFO] System.Data.Entity.Internal.Linq.InternalSet1.Initialize() [01/02/2018 10:59:16 > 395c4e: INFO] at System.Data.Entity.Internal.Linq.InternalSet1.get_InternalContext()[01/02/2018 .Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)[01/02/2018 10:59:16> 395c4e:INFO] 10:59:16> 395c4e:INFO]在System.Data.Entity.Infrastructure.DbQuery1.System.Linq.IQueryable.get_Provider() [01/02/2018 10:59:16 > 395c4e: INFO] at System.Linq.Queryable.Select[TSource,TResult](IQueryable1 source,Expression`1选择器)

这是我的启动类文件:

 public class Startup
    {
        private readonly IConfigurationRoot configuration;
        public Startup()
        {
            string environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

            var builder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{environment}.json", optional: true);

            configuration = builder.Build();
        }

        public void ConfigureServices(IServiceCollection services)
        {
            string sbConnectionString = configuration.GetValue<string>("ServiceBus:ConnectionString");
            string subscriptionName = configuration.GetValue<string>("ServiceBus:Subscription");
            bool isChinaRegion = configuration.GetValue<bool>("IsChinaRegion");
            services.AddSingleton<IServiceBusSettings>(sbSettings => new ServiceBusSettings(sbConnectionString, subscriptionName, isChinaRegion));

            string dbConnectionString = configuration.GetValue<string>("Database:ConnectionString");

            var compactDbContext = new CompactDbContext(dbConnectionString);

            services.AddTransient<DbContext>(dbContext => compactDbContext);

            services.AddTransient<IRepository<UserBasicInfo>, UserBasicInfoRepository>();
            services.AddTransient<IRepository<UserAdditionalInfo>, UserAdditionalInfoRepository>();
            services.AddTransient<IRepository<UserRoles>, UserRolesRepository>();

            services.AddTransient<IUserProfileRepository, UserProfileRepository>();

            services.AddSingleton<IServiceBusObjectProcessingStrategy<SerivceBusModel.ContractInfo>, ContractInfoProcessingStrategy>();
            services.AddTransient<IRepository<Registration>, RegistrationRepository>();
            services.AddTransient<ITempRegistrationRepository, TempRegistrationRepository>();


            services.AddLogging();
        }

        public void Configure(IServiceProvider serviceProvider)
        {
            if (configuration.GetValue<bool>("EnableDebugLogging"))
            {
                var loggerFactory = serviceProvider.GetService<ILoggerFactory>();
                var logLevel = configuration.GetValue<LogLevel>("DebugLoggingMinLevel");
                loggerFactory.AddConsole(logLevel);
                loggerFactory.AddDebug(logLevel);
            }
        }
    }
c# multithreading asp.net-core entity-framework-6 console-application
1个回答
0
投票

问题是您使用了Transient,但每次都返回相同的DbContext实例(即Singleton)。但是,如果多个人同时运行查询或者您在多个线程上运行多个查询,那么您将崩溃。相反,你只需要这样做:

services.AddTransient<DbContext>(dbContext => new CompactDbContext(dbConnectionString));
© www.soinside.com 2019 - 2024. All rights reserved.