Asp.Net核心dbcontext問題

asp.net-core entity-framework-core

我正在創建Asp.net核心應用程序並嘗試連接到數據庫。我在startup.cs文件中的ConfigureServices方法中的以下代碼行中收到錯誤。我得到的錯誤是值不能為空。好像它無法在web.config文件中找到CustomerOrderEntities鍵。不確定是什麼問題

services.AddDbContext<CustomerOrderEntities>(options =>
                  options.UseSqlServer(Configuration.GetConnectionString("CustomerOrderEntities")));

Startup.cs

 public IServiceProvider ConfigureServices(IServiceCollection services)
        {
services.AddDbContext<CustomerOrderEntities>(options =>
              options.UseSqlServer(Configuration.GetConnectionString("CustomerOrderEntities")));

 AutoMapperConfiguration.Configure();

            // Create the container builder.
            var builder = new ContainerBuilder();

            // Register dependencies, populate the services from
            // the collection, and build the container. If you want
            // to dispose of the container at the end of the app,
            // be sure to keep a reference to it as a property or field.


            builder.RegisterType<UnitOfWork>().As<IUnitOfWork>();
            builder.RegisterType<DbFactory>().As<IDbFactory>();
            builder.RegisterType<CustomerRepository>().As<ICustomerRepository>();
            builder.RegisterType<ProductRepository>().As<IProductRepository>();
            builder.RegisterType<OrderRepository>().As<IOrderRepository>();



            builder.Populate(services);
            this.ApplicationContainer = builder.Build();

            // Create the IServiceProvider based on the container.
            return new AutofacServiceProvider(this.ApplicationContainer);
          }

Web.Config中

<connectionStrings>

  <add name="CustomerOrderEntities" connectionString="metadata=res://*/EF.CustomerOrderContext.csdl|res://*/EF.CustomerOrderContext.ssdl|res://*/EF.CustomerOrderContext.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=test-PC\MSSQLSERVER2014;initial catalog=CodeFirstTest;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

  </connectionStrings>

一般承認的答案

ASP.NET Core中的連接字符串在appsettings.json中定義,例如:

"ConnectionStrings": {
    "CustomerOrderEntities": "Server=(localdb)\\mssqllocaldb;Database=aspnet-a3e892a5-6a9c-4090-bc79-fe8c79e1eb26;Trusted_Connection=True;MultipleActiveResultSets=true"
  },

在你的情況下,連接字符串的名稱是CustomerOrderEntities,你得到null,可能它不在那裡,檢查你appsettings.json。


熱門答案

你在Appsettings.json中的連接字符串肯定是丟失的。無論您是針對完整的.net框架還是.net核心,都無法在Asp.net核心的web.config中設置連接字符串。您可以在services.AddDbContext中鍵入連接字符串值(options => options.UseSqlServer(“Your Connectionstring”));有關更多信息,請點擊此處

https://docs.microsoft.com/en-us/ef/core/



Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因