简体   繁体   中英

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

When I execute my asp.net core console application using ASP.NET Core Console Application With EF6 . I'm getting the following error often.

System.InvalidOperationException: The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe. [01/02/2018 10:59:16 > 395c4e: INFO] at System.Data.Entity.Internal.LazyInternalContext.InitializeContext() [01/02/2018 10:59:16 > 395c4e: INFO] at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) [01/02/2018 10:59:16 > 395c4e: INFO] at 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)

It's my startup class file:

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

Issue is that you used Transient but have it return the same DbContext instance everytime (ie Singleton). However, if more than one person were to run a query at the same time or you run multiple queries on multiple threads, you are going to crash. Instead, you'd just do this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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