加入收藏 | 设为首页 | 会员中心 | 我要投稿 汽车网 (https://www.0577qiche.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

NetCore EF 配置DBContext By MsSql

发布时间:2023-05-09 13:11:00 所属栏目:MsSql教程 来源:
导读:配置DbContext
1.1.Startup / ConfigureServices

services.AddDbContext<CustDbContext>(options => options.UsesqlServer(configuration["ConnectionStrings:DefaultConnection"]));
如果不能注入Configuratio
配置DbContext
1.1.Startup / ConfigureServices

services.AddDbContext<CustDbContext>(options => options.UsesqlServer(configuration["ConnectionStrings:DefaultConnection"]));
如果不能注入Configuration,则为:

//读取配置文件
IConfiguration configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json", false, true).Build();
services.AddSingleton(configuration);
services.AddDbContext<CustDbContext>(options => options.UsesqlServer(configuration["ConnectionStrings:DefaultConnection"]));
1.2.CustDbContext

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UsesqlServer("Name=ConnectionStrings:DefaultConnection");
            }
        }
注入DbContext
2.1.通过 IServiceProvider 注入

provider.GetService<CustDbContext>()
2.2.构造函数注入

    public class CustClass
    {
        private readonly CustDbContext dbContext;
        public CustClass(CustDbContext _dbContext)
        {
            dbContext = _dbContext;
        }
    }

(编辑:汽车网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章