ASP.NET MVC5:无法添加具有自定义数据库上下文的新角色

ASP.NET MVC5: Unable to add new roles with custom db context

我的 ASP.NET MVC 项目的自定义数据库上下文遇到了一个非常令人厌恶的问题。

嗯,我一直在尝试将自动生成的 ApplicationDbContext 与我自己的 GSDbContext 合并,同时仍然保持 IdentityUsersIdentityRoles 正常工作。

这是我的自定义ApplicationUserclass定义:

 public class ApplicationUser : IdentityUser
{
    [Required]
    public string FirstAndLastName { get; set; }

    public bool Active { get; set; }
}

和上下文class:

public class GSDbContext : IdentityDbContext
{
     public GSDbContext()
          : base("GSDbContext")
     {
     }

     public virtual IDbSet<ApplicationUser> Users { get; set; }
     public virtual IDbSet<IdentityRole> Roles { get; set; }
     public virtual IDbSet<IdentityUserLogin> UserLogins { get; set; }
     public virtual IDbSet<IdentityUserClaim> UserClaims { get; set; }
     public virtual IDbSet<IdentityUserRole> UserRoles { get; set; }
}

现在发生的事情是,当我尝试添加新角色时,我得到 System.ArgumentNullException。顺便说一句,我可以轻松地创建一个新用户而不会感到痛苦。我使用此代码创建一个新用户:

var userManager = new UserManager<ApplicationUser>(
            new UserStore<ApplicationUser>(new GSDbContext()));
userManager.Create(user, password);

以及添加新角色:

var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new GSDbContext()));
roleManager.Create(new IdentityRole("Admin"));

抛出以下异常:

System.ArgumentNullException was unhandled by user code
  HResult=-2147467261
  Message=Value cannot be null.
Parameter name: source
  Source=System.Core
  ParamName=source
  StackTrace:
       at System.Linq.Queryable.Any[TSource](IQueryable`1 source, Expression`1 predicate)
       at Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext`1.ValidateEntity(DbEntityEntry entityEntry, IDictionary`2 items)
       at System.Data.Entity.DbContext.GetValidationErrors()
       at System.Data.Entity.Internal.InternalContext.SaveChangesAsync(CancellationToken cancellationToken)
       at System.Data.Entity.Internal.LazyInternalContext.SaveChangesAsync(CancellationToken cancellationToken)
       at System.Data.Entity.DbContext.SaveChangesAsync(CancellationToken cancellationToken)
       at System.Data.Entity.DbContext.SaveChangesAsync()
       at Microsoft.AspNet.Identity.EntityFramework.RoleStore`1.<CreateAsync>d__2.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
       at Microsoft.AspNet.Identity.RoleManager`1.<CreateAsync>d__0.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
       at Microsoft.AspNet.Identity.AsyncHelper.RunSync[TResult](Func`1 func)
       at Microsoft.AspNet.Identity.RoleManagerExtensions.Create[TRole](RoleManager`1 manager, TRole role)

这让我发疯了。

提前致谢。

不要将身份模型包含到您的 DbContext 中,它已包含在 IdentityDbContext 本身中。所以你可以像这样改变你的上下文:

public class GSDbContext : IdentityDbContext<ApplicationUser>
{
    // put your OTHER entities apart from identity related onces
    public IDbSet<MyModel> MyModels { get; set; }
    // and so on
}

您应该删除 IdentityDbContext 中已经存在的属性。

public class GSDbContext : IdentityDbContext
{
     public GSDbContext()
          : base("GSDbContext")
     {
     }
     public virtual IDbSet<ApplicationUser> Users { get; set; }
     //Nothing ELSE
}