c# - 错误提示。没有为此 DbContext 配置数据库提供程序
问题描述
我在访问数据库表中的数据时遇到错误,说InvalidOperationException: 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.
我使用了通用存储库模式。我在单独的类库项目中有我的 DbContext 即 BlazorContext 和模型类。
任何帮助都会很感激。
下面是我在 appsettings.json 中的连接字符串
"ConnectionStrings": {
"myconn": "server=DESKTOP-VM2VP34; database=BlazorDB;Trusted_Connection=True;"
},<br><br>
下面是我的startup.cs
services.AddDbContext<BlazorContext>(item => item.UseSqlServer(Configuration.GetConnectionString("myconn")));
下面是我的 DbContext 即 BlazorContext
namespace Blazor.Model.Models
{
public class BlazorContext:DbContext
{
public BlazorContext()
{
}
public BlazorContext(DbContextOptions<BlazorContext> options)
: base(options)
{
Database.EnsureCreated();
}
public DbSet<Person> Persons { get; set; }
}
}
下面是我的通用存储库实现,它显示错误
namespace Blazor.Repository.Implementation
{
public class GenericRepository<T> : IGenericRepository<T> where T : class
{
protected BlazorContext _entities;
protected readonly DbSet<T> _dbset; // error in this line
public GenericRepository(BlazorContext context)
{
_entities = context;
_dbset = context.Set<T>();
}
public IEnumerable<T> GetAll()
{
return _dbset.AsEnumerable();
}
}
}
下面是我的 GenericUnitOfWork
namespace Blazor.Repository.Implementation
{
public sealed class GenericUnitOfWork : IGenericUnitOfWork, IDisposable
{
private BlazorContext entities = null;
public GenericUnitOfWork()
{
entities = new BlazorContext();
}
public Dictionary<Type, object> repositories = new Dictionary<Type, object>();
public IGenericRepository<T> Repository<T>() where T : class
{
if (repositories.Keys.Contains(typeof(T)) == true)
{
return repositories[typeof(T)] as IGenericRepository<T>;
}
var t = typeof(T);
IGenericRepository<T> repo = new GenericRepository<T>(entities);//error in this line
repositories.Add(typeof(T), repo);
return repo;
}
}
}
解决方案
您的连接字符串模板不适用于 MS SQL 服务器。尝试使用这样的东西:
"Data Source=localhost;Initial Catalog=BlazorDB;Integrated Security=SSPI;Persist Security Info=True;"
如果它不起作用,那么您不使用 MS SQL 服务器,因此在您的启动中,您必须将“item => item.UseSqlServer”替换为其他提供程序。