2016-11-26 91 views
1

我正在创建Asp.net核心应用程序并尝试连接到数据库。我在startup.cs文件的ConfigureServices方法中的以下代码行中收到错误消息。我得到的错误是值不能为空。它似乎无法找到web.config文件中的CustomerOrderEntities项。不知道是什么问题Asp.Net核心dbcontext问题

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> 
+0

您确定您使用的是EntityFramework 6吗? reigstraiton看起来更像EFCore,而EF核心不使用web.config,但是你的appsettings.json(和本地开发的用户机密) – Tseng

+0

在asp.net核心中,我们不会在web.config中存储那种东西, web.config仅适用于IIS配置,您应该使用appsettings.json –

+0

对不起。它是entityframeworkcore而不是6 – Tom

回答

1

在ASP.NET核心连接字符串中appsettings.json定义,例如:

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

在你的情况下连接字符串的名字是CustomerOrderEntities,你得到null,可能它不在那里,检查你的appsettings.json。

0

您在Appsettings.json中的连接字符串肯定缺失。无论您是以.net framework还是.net core为完整目标,您都无法在Asp.net核心的web.config中设置连接字符串。另一种方法是在services.AddDbContext中输入连接字符串值(options => options.UseSqlServer(“Your Connectionstring”)); 欲了解更多信息,请点击这里;

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