我正在创建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="data source=test-PC\MSSQLSERVER2014;initial catalog=CodeFirstTest;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
您确定您使用的是EntityFramework 6吗? reigstraiton看起来更像EFCore,而EF核心不使用web.config,但是你的appsettings.json(和本地开发的用户机密) – Tseng
在asp.net核心中,我们不会在web.config中存储那种东西, web.config仅适用于IIS配置,您应该使用appsettings.json –
对不起。它是entityframeworkcore而不是6 – Tom