考虑使用IDbContextFactory在设计时覆盖DbContext的初始化。

4
在一个使用Entity Framework Core和ASP.NET Identity的ASP.NET Core 1.0.1项目中,我有以下上下文:
public class Context : IdentityDbContext<User, Role, Int32, UserClaim, UserRole, UserLogin, RoleClaim, UserToken> { 
  public Context(DbContextOptions options) : base(options) { }
  protected override void OnModelCreating(ModelBuilder builder) {
   base.OnModelCreating(builder);
  }
}

以下实体:
public class User : IdentityUser<Int32, UserClaim, UserRole, UserLogin> { }
public class Role : IdentityRole<Int32, UserRole, RoleClaim> { }
public class RoleClaim : IdentityRoleClaim<Int32> { }
public class UserClaim : IdentityUserClaim<Int32> { }
public class UserLogin : IdentityUserLogin<Int32> { }
public class UserRole : IdentityUserRole<Int32> { }
public class UserToken : IdentityUserToken<Int32> { }

在启动时,我有以下操作:
services.AddDbContext<Context>(x => x.UseSqlServer(connectionString, y => y.MigrationsHistoryTable("__Migrations")));

services
  .AddIdentity<User, Role>()
  .AddEntityFrameworkStores<Context, Int32>()
  .AddDefaultTokenProviders();

当我运行dotnet ef migrations add "FirstMigration"时,出现以下错误:

在启动类'WebProject.Startup'上调用方法'ConfigureServices'时发生错误。考虑使用IDbContextFactory在设计时覆盖DbContext的初始化。 错误:GenericArguments[0],'WebProject.User',在'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`4[TUser,TRole,TContext,TKey]'上违反了类型'TUser'的约束。

如何解决此问题?

你会在 RoleClaim、UserClaim、UserLogin、UserRole 或 UserToken 中编写任何自定义代码吗?如果不需要,你可以直接继承 Context : IdentityDbContext<User, Role, Int32>User : IdentityUser<Int32>Role : IdentityRole<Int32> - tmg
@tmg 我可能需要在这些地方编写一些自定义代码...这就是为什么我要这样使用它的原因。而且微软在 https://github.com/aspnet/Identity/blob/dev/src/Microsoft.AspNetCore.Identity.EntityFrameworkCore/IdentityDbContext.cs#L84 中添加了该选项。我现在只是不确定为什么会出现问题,因为似乎一切都很正常。 - Miguel Moura
我不确定错误来自哪里,也不知道为什么会得到“考虑使用IDbContextFactory”的建议。 - Miguel Moura
面对相同的问题,我只是想分享我的想法并继续调查...听起来像是DI/Generics的问题。也许我们需要一个自定义的UserStore! - Hossam
1
尝试运行 dotnet ef migrations add "FirstMigration" --verbose 命令,它将会提供完整的堆栈跟踪信息,有可能找到错误的来源。 - Segmentation Fault
1个回答

5

很抱歉我只回答了部分答案,但对许多人可能会有用...

启动类上的方法 'ConfigureServices' 的调用发生错误

您的方法 Startup.ConfigureServices(...) 正在被调用,并且它抛出了异常。该异常可能是由于在运行 dotnet ef 时,应用程序入口点不是像通常一样的 Program.Main()

尝试:

    dotnet ef migrations add "FirstMigration" --verbose 

这将打印错误消息,帮助您更好地理解问题。


1
学习了解程序,Main()不是入口点,使用dotnet ef migrations add "FirstMigration" --verbose帮助我解决了这个问题。 - ttugates

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接