【发布时间】:2017-10-28 12:24:52
【问题描述】:
我有一个 .Net Core WebApplication 项目,其中上下文类位于类库中。如果我在 OnConfiguring(DbContextOptionsBuilder optionsBuilder) 方法中硬编码连接字符串,我可以生成迁移。由于最好让依赖注入管理上下文,因此我想将其添加到启动类中。但是,当我这样做时,会出现以下错误:
没有为此 DbContext 配置数据库提供程序。可以通过重写 DbContext.OnConfiguring 方法或在应用程序服务提供者上使用 AddDbContext 来配置提供者。如果使用了 AddDbContext,那么还要确保您的 DbContext 类型在其构造函数中接受 DbContextOptions 对象并将其传递给 DbContext 的基本构造函数。
DbContext 类:
public class CustomerManagerContext : IdentityDbContext<User, Role, long, UserClaim, UserRole, UserLogin, RoleClaim, UserToken>
{
public CustomerManagerContext() { }
public CustomerManagerContext(DbContextOptions<CustomerManagerContext> options) : base(options)
{
}
//protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
//{
// base.OnConfiguring(optionsBuilder);
// optionsBuilder.UseSqlServer("SecretConnectionString");
//}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<User>().ToTable("Users");
builder.Entity<Role>().ToTable("Roles");
builder.Entity<UserClaim>().ToTable("UserClaims");
builder.Entity<UserRole>().ToTable("UserRoles");
builder.Entity<UserLogin>().ToTable("UserLogins");
builder.Entity<RoleClaim>().ToTable("RoleClaims");
builder.Entity<UserToken>().ToTable("UserTokens");
}
}
启动类 - ConfigureServices 方法
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<CustomerManagerContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
);
services.AddEntityFrameworkSqlServer()
.AddDbContext<CustomerManagerContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<User, Role>()
.AddEntityFrameworkStores<CustomerManagerContext>()
.AddDefaultTokenProviders();
}
【问题讨论】:
-
不完全确定,但对我来说,您同时使用
AddDbContext和AddEntityFrameworkSqlServer听起来完全不正确(而且您在这里也调用UseSqlServer)。尝试注释掉对AddEntityFrameworkSqlServer的调用 -
@CamiloTerevinto 我已尝试将两者都注释掉,但都没有。奇怪的是,如果我使用 OnConfiguring 设置有效。我必须错过一些东西。
-
您也可以尝试删除两个构造函数,或者至少删除无参数的构造函数
-
@CamiloTerevinto 如果我删除两个构造函数,我会得到相同的错误。如果我只是删除无参数的,我会收到以下错误。在“CustomerManagerContext”上找不到无参数构造函数。将无参数构造函数添加到“CustomerManagerContext”或在与“CustomerManagerContext”相同的程序集中添加“IDbContextFactory
”的实现。 PM> add-migration Initial -
@Dblock247:您不应该同时删除
.AddDbContext和AddEntityFrameworkSqlServer,只删除AddEntityFrameworkSqlServer一个。我怀疑它是因为两者都注册了DbContextOptionsBuilder的两个实例,并且当DI 尝试通过provider.GetRequiredService<T>()解决它时,当有多个注册时它会失败。一个以上的注册只能通过GetRequiredServices(复数)解决
标签: c# asp.net-core entity-framework-core entity-framework-migrations