【发布时间】:2015-12-07 21:50:52
【问题描述】:
我为我的应用程序扩展了 AspNetUserRoles,我在 AspNetUserRoles 表中添加了一个新的 FK 列 ApplicationId。这背后的想法是允许同一用户在具有相同或不同角色的不同应用程序中。
一切似乎都很好,直到我尝试将相同的角色添加到同一个用户但对于我开始收到错误的不同应用程序:
违反主键约束“PK_dbo.AspNetUserRoles”。不能 在对象 'dbo.AspNetUserRoles' 中插入重复键。
请任何人帮助我摆脱这个问题。
我的身份模型如下
public class ApplicationUser : IdentityUser
{
public virtual AspNetApplications AspNetApplication { get; set; }
public virtual AspNetUserRoles AspNetUserRoles { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
public DbSet<AspNetApplications> AspNetApplications { get; set; }
public DbSet<AspNetUserRoles> AspNetUserRoles { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
我的 AspNetApplications 和 AspNetUserRoles 模型如下
public class AspNetApplications
{
[Key]
public string ApplicationId { get; set; }
public string ApplicationName { get; set; }
}
public class AspNetUserRoles : IdentityUserRole
{
[Key]
public string ApplicationId { get; set; }
[ForeignKey("ApplicationId")]
public AspNetApplications AspNetApplications { get; set; }
}
以下是我添加 AspNetUserRoles 类型的新实体的代码,它在 dbContext.SaveChanges() 处引发错误
var aspNetUserRole = new AspNetUserRoles
{
UserId = userId,
RoleId = roleId,
ApplicationId = applicationId,
};
dbContext.AspNetUserRoles.Add(aspNetUserRole);
dbContext.SaveChanges();
【问题讨论】:
标签: asp.net-mvc asp.net-identity asp.net-identity-2 user-roles