【发布时间】:2016-11-19 05:18:18
【问题描述】:
我正在尝试仅使用 AspNetUsers、AspNetRoles 和 AspNetUserRoles 自定义 EntityFrameworkCore 身份......这可能吗?
我的代码:
ApplicationUser.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>>();
}
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.AddIdentity<ApplicationUser, IdentityRole<int>>()
.AddEntityFrameworkStores<ApplicationDbContext, int>()
.AddDefaultTokenProviders();
...
}
AccountController.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,因为该类型未包含在上下文。
我的数据库只包含表 AspNetRoles、AspNetUsers 和 AspNetUserRoles 与默认列(Id 的类型 int)。
谢谢。
【问题讨论】:
-
为什么要忽略
IdentityUserClaim等额外的4行? -
Ignore IdentityUserLogin != InvalidOperationException:实体类型“Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin
”需要定义一个键。 -
没有额外的行返回 -> IdentityUserLogin
需要定义一个键。 IdentityUserToken 需要定义一个键。 SqlException:对象名称“UserClaims”无效。 SqlException:无效的对象名称“RolerClaims”。 -
您找到解决方案了吗?
标签: c# asp.net-mvc entity-framework authentication asp.net-identity