我想與AspNetUsers,AspNetRoles和AspNetUserRoles自定義EntityFrameworkCore身份...這可能嗎?自定義標識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)。
感謝。
爲什麼額外的4行忽略'IdentityUserClaim'等? – DavidG
忽略IdentityUserLogin!= InvalidOperationException:實體類型'Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin'需要定義一個密鑰。 –
沒有額外的行返回 - > IdentityUserLogin要求定義一個關鍵。 IdentityUserToken 需要定義一個密鑰。 SqlException:無效的對象名稱'UserClaims'。 SqlException:無效的對象名稱'RolerClaims'。 –