Я расширил AspNetUserRoles для своего приложения, добавив новый столбец FK ApplicationId
в таблицу AspNetUserRoles
. Идея заключается в том, чтобы позволить одному и тому же пользователю находиться в разных приложениях с одинаковыми или разными ролями. Кажется, все в порядке, пока я не попытался добавить ту же роль для того же пользователя, но для другого приложения, где я начал получать ошибку:
Нарушение ограничения PRIMARY KEY «PK_dbo.AspNetUserRoles». Не удается вставить повторяющийся ключ в объект «dbo.AspNetUserRoles».
Может ли кто-нибудь помочь мне выйти из этой проблемы.
мои IdenitityModels следующие
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();