Asp.Net核心dbcontext问题

时间:2016-11-26 18:08:06

标签: 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>

2 个答案:

答案 0 :(得分:1)

Connection string in ASP.NET Core is defined in appsettings.json, for example:

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

In your case name of connecting string is CustomerOrderEntities, you get null, probably it's not there, check you appsettings.json.

答案 1 :(得分:0)

您在Appsettings.json中的连接字符串肯定是缺失的。无论是针对完整的.net框架还是.net核心,都无法在Asp.net核心的web.config中设置连接字符串。您可以选择在services.AddDbContext中键入连接字符串值(options =&gt;               options.UseSqlServer(“Your Connectionstring”)); 有关更多信息,请点击此处;

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