1. 程式人生 > 其它 >使用netcore自帶的di來使用efcore

使用netcore自帶的di來使用efcore

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; }