在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)
在ConfigureServices(IServiceCollection服务)中,我试图在lambda中为我的DbContext指定DbContextOptions。 码:
services.AddEntityFramework(Configuration) .AddSqlServer() .AddDbContext( options => options.UseSqlServer(Configuration.Get("Data:DefaultConnection:ConnectionString")) );
在我的DbContext中,我有一个构造函数,它将选项发送到base,代码:
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方式。
如果需要更多信息,我会提供。
您是否将您的上下文注入您的控制器或您使用它的任何地方? 我发现如果你尝试新建上下文而不是注入它,它就不会使用Startup.cs中指定的配置
我(仍)在EF7和beta 4上遇到同样的问题。这是我的数据上下文中的解决方法:
public class AspNetDataContext : IdentityDbContext, IDataContext { private readonly string _connectionString; public DbSet Players { get; set; } public AspNetDataContext(DbContextOptions options) { _connectionString = ((SqlServerOptionsExtension)options.Extensions.First()).ConnectionString; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(_connectionString); } }
我从选项中提取connectionstring并在OnConfiguring方法中使用它。 这仍然不是我们想要的解决方案,但我不需要在Startup.cs中改变一些东西(就像你描述的那样)。 并且一旦修复,您只需要从数据上下文类中删除这些东西。 也许有人有另一个(甚至更好)解决这个问题的方法。
EF7具有从DBContextOptionsBuilder到EntityOptionsBuilder的新sytax。 以下是准备用于命令行脚手架。
public class ContentContext : DbContext { public DbSet Contents { get; set; } public DbSet ContentCategories { get; set; } protected override void OnConfiguring(EntityOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("Data:DefaultConnection:ConnectionString"); } }
- 让autofac与mvc6 beta5一起使用
- Asp网核rc2。 抽象类模型绑定
- 如何关闭ASP.NET核心框架完成的日志记录
- 无法让ASP.NET MVC 6 Controller返回JSON
- ASP.NET5 MVC6的模型绑定问题
- 在ASP.NET Core MVC API控制器上对AuthorizeAttribute进行unit testing
- ASP.NET Core RC2和.NET 4.5.1应用程序之间的共享cookie身份validation
- ASP.NET 5中Global.json中项目部分的说明
- Azure Web应用程序服务,使用混合连接管理器使用HttpClient调用onpremise WEB API