小编Dan*_*lRJ的帖子

在Startup.cs中添加DbContextOptions而不注册数据存储

我的问题是下面的代码在启动期间没有注册数据存储.这是我在应用程序的响应中得到的特定"错误"语句:

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)
Run Code Online (Sandbox Code Playgroud)

在ConfigureServices(IServiceCollection服务)中,我试图在lambda中为我的DbContext指定DbContextOptions.码:

services.AddEntityFramework(Configuration)
    .AddSqlServer()
    .AddDbContext<MyDbContext>(
        options =>
        options.UseSqlServer(Configuration.Get("Data:DefaultConnection:ConnectionString"))
    );
Run Code Online (Sandbox Code Playgroud)

在我的DbContext中,我有一个构造函数,它将选项发送到base,代码:

public MyContext(DbContextOptions options) : base(options) { }
Run Code Online (Sandbox Code Playgroud)

我的配置文件config.json在启动时读取,包含以下连接字符串:

"Data": {
    "DefaultConnection": {
        "ConnectionString": "Server=(localdb)\\MSSQLLocalDB;Database=MyDbName;Trusted_Connection=True;MultipleActiveResultSets=True;"
    }
}
Run Code Online (Sandbox Code Playgroud)

我以前用过

protected override void OnConfiguring(DbContextOptions options)
{
    options.UseSqlServer(Startup.Configuration.Get("Data:DefaultConnection:ConnectionString"));

}
Run Code Online (Sandbox Code Playgroud)

在我的DbContext中成功.它注册数据存储并且它正常工作,但我宁愿使用lambda方式.

如果需要更多信息,我会提供.

c# entity-framework dependency-injection entity-framework-core asp.net-core-mvc

10
推荐指数
1
解决办法
1万
查看次数