C#/.Net6.0 依赖注入,读取的数据库配置文件不生效

        最近用.net6.0开发后台API,使用EF6+Mysql数据库,在调用DbContext的时候报了一个错"No database provider has been configured for this DbContext. A provider can be configured by overriding the 'DbContext.OnConfiguring' method or by using 'AddDbContext' on the application service provider. If 'AddDbContext' is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext."

        看这意思好像没有配置数据库,可是我明明在Program.cs里面配置了,并且注入了。题主百思不得其解,抓耳挠腮了一下午。

#region 调用自定义的依赖注入
builder.Services.FinernConfigureServices(Configuration);

builder.Services.AddDbContext<apidataContext>(
    options => options.UseMySql(builder.Configuration.GetConnectionString("ConnectionString"), Microsoft.EntityFrameworkCore.ServerVersion.Parse("8.0.24-mysql"))
        );

#endregion

        最后找大佬解惑,有两种解决办法,废话不多说上代码:

第一种重写DbContext的OnConfiguring方法,每次生成一个DbContext的方法的时候就会重新来这个方法这里读一下配置:

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseMySql("server=*.*.*.*;port=****;user id=root;password=******;database=******;charset=utf8", Microsoft.EntityFrameworkCore.ServerVersion.Parse("8.0.24-mysql"));
            }
        }

第二种就是在已经注入的情况下,就不再需要自己去New一个对象了,直接在使用的地方把DbContext 当成构造参数传进来

问题轻松解决,这里记个笔记,希望能帮到有同样疑惑的朋友:)

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值