我的问题是下面的代码在启动期间没有注册数据存储。这是我在应用程序响应中得到的特定“错误”语句:
An unhandled exception occurred while processing the request.
InvalidOperationException: No data stores are configured. Configure a data store by overriding OnConfiguring in your DbContext class or in the AddDbContext method when setting up services.
Microsoft.Data.Entity.Storage.DataStoreSelector.SelectDataStore(ServiceProviderSource providerSource)
在ConfigureServices(IServiceCollection services) 中,我尝试在lambda 中为我的DbContext 指定DbContextOptions。代码:
services.AddEntityFramework(Configuration)
.AddSqlServer()
.AddDbContext<MyDbContext>(
options =>
options.UseSqlServer(Configuration.Get("Data:DefaultConnection:ConnectionString"))
);
在我的 DbContext 中,我有一个构造函数,它将选项发送到基础代码:
public MyContext(DbContextOptions options) : base(options) { }
我的配置文件 config.json 在启动时读取,包含以下连接字符串:
"Data": {
"DefaultConnection": {
"ConnectionString": "Server=(localdb)\\MSSQLLocalDB;Database=MyDbName;Trusted_Connection=True;MultipleActiveResultSets=True;"
}
}
我以前用过
protected override void OnConfiguring(DbContextOptions options)
{
options.UseSqlServer(Startup.Configuration.Get("Data:DefaultConnection:ConnectionString"));
}
在我的 DbContext 中成功。它注册了数据存储并且工作正常,但我宁愿使用 lambda 方式。
如果需要更多信息,我会提供。