![](/img/trans.png)
[英]Why does EF7 say I haven't configured any providers, when ASP.net Identity is working fine with the same DbContext?
[英]No database providers are configured EF7
使用Entity Framework 7和MVC6时似乎收到此错误消息
System.InvalidOperationException没有配置数据库提供程序。 在设置服务时,通过覆盖DbContext类或AddDbContext方法中的OnConfiguring来配置数据库提供程序。
我相信我已经做了我应该做的所有事情,所以也许是个错误。 我正在使用7.0.0-beta7版本的Entity Framework。
我已经设置了我的DbContext接口,以便可以模拟DbContext(在EntityFramework 6中需要进行单元测试)。 我的服务将接口用作构造函数,并且在MVC 6中设置了DI。
在我的Startup.cs文件中,我有以下内容
public void ConfigureServices(IServiceCollection services)
{
// entity framework
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<MyDbContext>(options =>
options.UseSqlServer(Configuration["Data:MyConnection:ConnectionString"])
);
// Add MVC services to the services container.
services.AddMvc();
// new context on each request
services.AddScoped<IMyDbContext, MyDbContext>();
}
我已经检查了我的connectionString,并且返回了一个有效的连接。 我还检查了服务是否已注入该对象,并且该对象不为null,因此应该可以正常工作。
我的config.json文件看起来像这样
{
"Data": {
"MyConnection": {
"ConnectionString": "Server=(local);Database=XXXX;Trusted_Connection=True;"
}
}
}
我的DbContext不会覆盖OnConfiguring方法,因为我认为不需要,因为如上所述,我正在这样做? 我对吗? 我想念什么? 看了很多不同的网站,我猜有些正在使用旧代码,因为某些方法不存在,其他网站与我拥有的相同。
设置如下所示的MyDbContext,以注入Startup.cs AddDbContext()调用中定义的options参数。
public MyDbContext(DbContextOptions options)
: base(options)
{ }
这将允许您将连接字符串从Configuration(config.json)传递到方法调用选项中。
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<MyDbContext>(options => options.UseSqlServer(Configuration["Data:MyConnection:ConnectionString"]));
当我不得不将解决方案拆分为单独的项目Web,BL和DAL时,我遇到了相同的问题。
我相信您在尝试从数据库访问某些数据的行上遇到了此错误。 您可以通过混淆上下文来解决此问题。 只需重写OnConfiguring方法即可。
public class MyDbContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlServer("<your connection string>");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
...
}
}
几周前,我在Visual Studio 2015中遇到了这个问题。
我必须将Context添加到startup.cs中的依赖项注入集合中。
请尝试以下操作:
public class DataContext<TEntity> : DbContext where TEntity : class
{
private TEntity _entity = null;
public DataContext()
: base()
{
}
public DataContext(TEntity entity)
{
this._entity = entity;
}
public DbSet<TEntity> Entity { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.HasDefaultSchema("dbo");
}
public IConfigurationRoot Configuration { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json");
Configuration = configuration.Build();
optionsBuilder.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.