我的 ASP.NET MVC 项目的自定义数据库上下文有一个非常令人作呕的问题。
好吧,我一直在尝试将自动生成ApplicationDbContext
的与我自己的合并,GSDbContext
同时仍然保持IdentityUsers
和IdentityRoles
工作。
这是我的自定义ApplicationUser
类定义:
public class ApplicationUser : IdentityUser
{
[Required]
public string FirstAndLastName { get; set; }
public bool Active { get; set; }
}
和上下文类:
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)
这让我非常疯狂。
提前致谢。