关于VS2017 添加 EF的MVC控制器报错的解决方法

1. 错误描述 :no database provider has been configured fot this DbContext.

此类错误是上下文的注册造成的.解决方式在DBContext中重写OnConfiguring方法去注入数据库连接.

DbContext中:

public  static string ConnectionString { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseSqlServer(ConnectionString);
    base.OnConfiguring(optionsBuilder);
}

在Startup.cs中

 public void ConfigureServices(IServiceCollection services)
 {
            // Add framework services.
            var sqlserverConnection = Configuration.GetConnectionString("SQLServerConnection");
            DbContext.ConnectionString = sqlserverConnection;//将配置连接传入DbContext中
            services.AddDbContext<DbContext>(options => options.UseSqlServer(sqlserverConnection));
        
            services.AddMvc();
}

 

2.错误描述:Could not add Model type XXX to DbContext

错误描述没有注册DbSet属性.但实际上是有 public DbSet<XXX> XXX{ get; set; }注册的.将DbSet<XXX>中的类改成<命名空间+类名>这种完整声明即可解决

posted @ 2017-04-18 14:00  Tweet  阅读(937)  评论(0编辑  收藏  举报