![](/img/trans.png)
[英]A provider can be configured by overriding the DbContext.OnConfiguring
[英]No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring
我在 .NET Core 3.1 Web Z72664DC0959F3B0C043891A 項目中的Startup
class 中有此數據庫配置。
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 static class RegisterDbContext
{
public static void RegisterAbcSqlServer<T>(this IServiceCollection services, string connectionString)
where T : DbContext, IAbcContext
{
var migrationsAssembly = typeof(RegisterDbContext).GetTypeInfo().Assembly.GetName().Name;
services.AddDbContext<T>(options => options.UseSqlServer(connectionString,
sql => sql.MigrationsAssembly(migrationsAssembly)));
}
public static void RegisterXyzSqlServer<T>(this IServiceCollection services, string connectionString)
where T : DbContext, IXyzContext
{
var migrationsAssembly = typeof(RegisterDbContext).GetTypeInfo().Assembly.GetName().Name;
services.AddDbContext<T>(options => options.UseSqlServer(connectionString,
sql => sql.MigrationsAssembly(migrationsAssembly)));
}
}
我可以毫無錯誤地構建。 但是當我執行 EF Core 添加遷移時,它會遇到錯誤:
沒有為此 DbContext 配置數據庫提供程序。 可以通過覆蓋 DbContext.OnConfiguring 方法或在應用程序服務提供者上使用 AddDbContext 來配置提供者。 如果使用 AddDbContext,則還要確保您的 DbContext 類型在其構造函數中接受 DbContextOptions object 並將其傳遞給 DbContext 的基本構造函數。
當 DI 框架無法通過注入DbContextOptions
來配置提供程序時,您可能會收到此錯誤。 所以你只需要添加一個可以接受的構造函數,或者為要傳入的DbContextOptions
添加一個參數。例如:
public class XYZContext : DbContext
{
// Add this constructor
public XYZContext (DbContextOptions options) : base(options)
{
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.