我正在尝试仅使用AspNetUsers,AspNetRoles和AspNetUserRoles自定义EntityFrameworkCore Identity...可能吗?
我的代码:
应用程序用户.cs
public class ApplicationUser : IdentityUser<int>
{
}
ApplicationDbContext.cs
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole<int>, int>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
//base.OnModelCreating(builder);
builder.Entity<IdentityUser<int>>().ForSqlServerToTable("AspNetUsers")
//.Ignore(x => x.Claims)
//.Ignore(x => x.Logins)
.HasKey(x => x.Id);
builder.Entity<IdentityRole<int>>().ForSqlServerToTable("AspNetRoles")
//.Ignore(x => x.Claims)
.HasKey(x => x.Id);
builder.Entity<IdentityUserRole<int>>().ForSqlServerToTable("AspNetUserRoles")
.HasKey(x => new { x.UserId, x.RoleId });
builder.Ignore<IdentityUserLogin<int>>();
builder.Ignore<IdentityUserToken<int>>();
builder.Ignore<IdentityUserClaim<int>>();
builder.Ignore<IdentityRoleClaim<int>>();
}
}
启动.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.AddIdentity<ApplicationUser, IdentityRole<int>>()
.AddEntityFrameworkStores<ApplicationDbContext, int>()
.AddDefaultTokenProviders();
...
}
帐户控制器.cs
public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
{
...
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToLocal(returnUrl);
}
AddErrors(result);
}
return View(model);
}
CreateAsync = 成功,但 SignInAsync 返回 InvalidOperationException: 无法为"IdentityUserClaim'1"创建 DbSet,因为此类型未包含在上下文的模型中。
我的数据库只包含带有默认列(Id 的类型 int)的 AspNetRoles、AspNetUsers 和 AspNetUserRoles 表。
谢谢。
我有一个类似的问题,但我创建了一个继承的 XXXRole。错误是:无法为"XXXRole"创建数据库集,因为此类型未包含在上下文的模型中。
事实证明,我还需要让 AppDbContext 知道正在使用哪个角色,否则它会假设......
所以我把它添加到IdentityDbContext的泛型类型中:
public class ApplicationDbContext : IdentityDbContext<XXXUser, XXXRole, string>
{
....
}
在上面的例子中,我建议你创建一个继承自"IdentityRole"的新的具体类。然后,您将执行以下操作:
public class ApplicationDbContext : IdentityDbContext<XXXUser, XXXRole, int>
{
....
}
我相信用户和角色使用相同的数据类型的键 - 所以你可能还需要创建 XXXUser:身份用户
我偶然发现了同样的问题,即使你的错误是愚蠢的,它在未来可以帮助某人:
我命名了
public class IdentityDbContext: IdentityDbContext<User>
{
....
}
当我引用它时,我没有指定它应该从哪个命名空间IdentityDbContext
(*正确的是MyNamespace.IdentityDbContext
(doh! )