關於VS2017 添加 EF的MVC控制器報錯的解決方法

1. 錯誤描述 :no database provider has been configured fot this DbContext.sql

此類錯誤是上下文的註冊形成的.解決方式在DBContext中重寫OnConfiguring方法去注入數據庫鏈接.數據庫

DbContext中:ide

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

在Startup.cs中sqlserver

 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 DbContextui

錯誤描述沒有註冊DbSet屬性.但其實是有 public DbSet<XXX> XXX{ get; set; }註冊的.將DbSet<XXX>中的類改爲<命名空間+類名>這種完整聲明便可解決this

相關文章
相關標籤/搜索