C# 尚未为此DbContext配置任何数据库提供程序。可以通过重写DbContext.onconfig来配置提供程序
我在.NET Core 3.1 Web Api项目中的C# 尚未为此DbContext配置任何数据库提供程序。可以通过重写DbContext.onconfig来配置提供程序,c#,entity-framework-core,C#,Entity Framework Core,我在.NET Core 3.1 Web Api项目中的启动类中有此数据库配置 public void ConfigureServices(IServiceCollection services) { var abcConnString = Configuration.GetConnectionString("abcConnString"); services.RegisterAbcSqlServer<ABCContext>(
启动
类中有此数据库配置
public void ConfigureServices(IServiceCollection services)
{
var abcConnString = Configuration.GetConnectionString("abcConnString");
services.RegisterAbcSqlServer<ABCContext>(abcConnString);
var xyzConnString = Configuration.GetConnectionString("xyzConnString");
services.RegisterXyzSqlServer<XYZContext>(xyzConnString);
// code removed for brevity.
}
public void配置服务(IServiceCollection服务)
{
var abcconstring=Configuration.GetConnectionString(“abcconstring”);
services.RegisterAbcSqlServer(abcConnString);
var xyzConnString=Configuration.GetConnectionString(“xyzConnString”);
注册表xyzsqlserver(xyzConnString);
//为简洁起见,删除了代码。
}
及
公共静态类RegisterDbContext
{
公共静态void RegisterAbcSqlServer(此IServiceCollection服务,字符串连接字符串)
其中T:DbContext,IAbcContext
{
var migrationassembly=typeof(RegisterDbContext).GetTypeInfo().Assembly.GetName().Name;
services.AddDbContext(options=>options.UseSqlServer(connectionString,
sql=>sql.migrationassembly(migrationassembly));
}
公共静态无效注册表XYZSQLServer(此IServiceCollection服务,字符串连接字符串)
其中T:DbContext,IXyzContext
{
var migrationassembly=typeof(RegisterDbContext).GetTypeInfo().Assembly.GetName().Name;
services.AddDbContext(options=>options.UseSqlServer(connectionString,
sql=>sql.migrationassembly(migrationassembly));
}
}
我可以建立没有错误。但当我执行EF Core添加迁移时,它会出现错误:
尚未为此DbContext配置任何数据库提供程序。A.
可以通过重写DbContext.onconfig来配置提供程序
方法或在应用程序服务提供程序上使用AddDbContext。
如果使用了AddDbContext,那么还要确保您的DbContext类型
在其构造函数中接受DbContextOptions对象,然后
将其传递给DbContext的基构造函数
当DI框架无法通过注入
DbContextOptions
来配置提供程序时,可能会出现此错误。因此,您只需要添加一个接受构造函数的构造函数,或者为要传入的DbContextOptions
添加一个参数。例如:
public class XYZContext : DbContext
{
// Add this constructor
public XYZContext (DbContextOptions options) : base(options)
{
}
}
您的
DbContext
看起来像什么?您是否有一个构造函数接受DbContextOptions
?哦,我的一个上下文错过了它的构造函数。谢谢大卫
public class XYZContext : DbContext
{
// Add this constructor
public XYZContext (DbContextOptions options) : base(options)
{
}
}