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

时间:2018-01-02 12:13:03

标签: c# multithreading asp.net-core entity-framework-6 console-application

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

  

System.InvalidOperationException:创建模型时无法使用上下文。如果在OnModelCreating方法中使用上下文,或者同时由多个线程访问相同的上下文实例,则可能抛出此异常。请注意,DbContext和相关类的实例成员不保证是线程安全的。   [01/02/2018 10:59:16> System.Data.Entity.Internal.LazyInternalContext.InitializeContext()中的395c4e:INFO]   [01/02/2018 10:59:16> System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)中的395c4e:INFO]   [01/02/2018 10:59:16> 395c4e:INFO]在System.Data.Entity.Internal.Linq.InternalSet 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] at 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 source,Expression`1 selector)

这是我的启动类文件:

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

1 个答案:

答案 0 :(得分:0)

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

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