最近用.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 当成构造参数传进来
问题轻松解决,这里记个笔记,希望能帮到有同样疑惑的朋友:)