netcore自带di的常规用法 https://www.cnblogs.com/wholeworld/p/9376137.html
先有db的情况下使用code first
流程:
添加类库项目
nuget 安装上 ef 反向工程需要的包,
包管理器控制台执行命令:
Scaffold-DbContext "Server=.;Database=db;uid=sa;pwd=123" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
添加网站项目,并引用上面的db项目
Startup文件
public void ConfigureServices(IServiceCollection services) { services.AddDbContext<db1Context>(options => options.UseSqlServer(Configuration.GetConnectionString("db1")), ServiceLifetime.Transient); services.AddDbContext<db2Context>(options => options.UseSqlServer(Configuration.GetConnectionString("db2")), ServiceLifetime.Transient); services.AddControllersWithViews(); }
控制器中使用db,有多种方式:
public IActionResult test_1([FromServices] db1Context db1, [FromServices] db2Context db2) { ... }
private readonly ILogger<HomeController> _logger; private readonly db1Context _db1; private readonly db2AccessContext _db2; public HomeController(ILogger<HomeController> logger, db1Context db1,db2Context db2) { _logger = logger; _db1 = db1; _db2 = db2; }