繁体   English   中英

使用带有EF 6的ASP.NET Core控制台应用程序“创建模型时无法使用上下文”

[英]“Context cannot be used while the model is being created” using ASP.NET Core Console Application With EF 6

当我使用带有EF6 ASP.NET Core Console Application执行ASP.NET Core Console应用程序时。 我经常遇到以下错误。

System.InvalidOperationException:创建模型时不能使用上下文。 如果在OnModelCreating方法内部使用上下文,或者多个线程同时访问同一上下文实例,则可能引发此异常。 请注意,不能保证DbContext和相关类的实例成员是线程安全的。 [01/02/2018 10:59:16> 395c4e:INFO]在System.Data.Entity.Internal.LazyInternalContext.InitializeContext()[01/02/2018 10:59:16> 395c4e:INFO]在System.Data System.Data.Entity.Internal.Linq.InternalSet 1.Initialize() [01/02/2018 10:59:16 > 395c4e: INFO] at System.Data.Entity.Internal.Linq.InternalSet TypeEntityType)[01/02/2018 10:59:16> 395c4e:INFO]在1.Initialize() [01/02/2018 10:59:16 > 395c4e: INFO] at System.Data.Entity.Internal.Linq.InternalSet 1.get_InternalContext()[01/02/2018 10:59:16> 395c4e:INFO]在System.Data.Entity .Infrastructure.DbQuery 1.System.Linq.IQueryable.get_Provider() [01/02/2018 10:59:16 > 395c4e: INFO] at System.Linq.Queryable.Select[TSource,TResult](IQueryable 1源,表达式`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);
            }
        }
    }

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

services.AddTransient<DbContext>(dbContext => new CompactDbContext(dbConnectionString));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM