我在 Visual Studio 2019 上使用 EF-Core 3.1 在 ASP.NET-Core 3.1 应用程序中扩展了 IdentityUser,并且我定义了以下字段
public class ApplicationUser : IdentityUser
{
public string Surname { get; set; }
public string OtherNames { get; set; }
...
public string RegistrarId { get; set; }
...
[ForeignKey("RegistrarId")]
public virtual ApplicationUser Registrar { get; set; }
....
}
这是所有需要进一步关系的实体的 fluentApi
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUser>(b =>
{
// Each User can have many UserClaims
b.HasMany(e => e.Claims)
.WithOne(e => e.User)
.HasForeignKey(uc => uc.UserId)
.IsRequired();
// Each User can have many UserLogins
b.HasMany(e => e.Logins)
.WithOne(e => e.User)
.HasForeignKey(ul => ul.UserId)
.IsRequired();
// Each User can have many UserTokens
b.HasMany(e => e.Tokens)
.WithOne(e => e.User)
.HasForeignKey(ut => ut.UserId)
.IsRequired();
// Each User can have many entries in the UserRole join table
b.HasMany(e => e.UserRoles)
.WithOne(e => e.User)
.HasForeignKey(ur => ur.UserId)
.IsRequired();
b.HasIndex(e => e.Email)
.IsUnique();
});
modelBuilder.Entity<ApplicationRole>(b =>
{
// Each Role can have many entries in the UserRole join table
b.HasMany(e => e.UserRoles)
.WithOne(e => e.Role)
.HasForeignKey(ur => ur.RoleId)
.IsRequired();
// Each Role can have many associated RoleClaims
b.HasMany(e => e.RoleClaims)
.WithOne(e => e.Role)
.HasForeignKey(rc => rc.RoleId)
.IsRequired();
b.HasMany(e => e.RoleRoutes)
.WithOne(e => e.Role)
.HasForeignKey(c => c.RoleId)
.IsRequired();
});
modelBuilder.Entity<RatedGroupCriterion>()
.HasKey(rc => new {
rc.RatedGroupId,
rc.CriterionId
});
modelBuilder.Entity<RatedGroupCriterion>()
.HasOne(reg => reg.RatedGroup)
.WithMany(rgc => rgc.RelatedCriteria)
.HasForeignKey(reg => reg.RatedGroupId);
modelBuilder.Entity<RatedGroupCriterion>()
.HasOne(rc => rc.Criterion)
.WithMany(rgc => rgc.RelatedEntities)
.HasForeignKey(reg => reg.CriterionId);
modelBuilder.Entity<InstructorCriterionRating>()
.HasKey(irc => new { irc.InstructorRatingId, irc.CriterionId });
modelBuilder.Entity<LessonCriterionRating>().HasKey(lrc => new { lrc.LessonRatingId, lrc.CriterionId });
modelBuilder.Entity<RoleErrand>().HasKey(rap => new { rap.RoleId, rap.ErrandId });
modelBuilder.Seed();
}
但我意识到在将第一条记录插入数据库表后,我在将更多记录插入同一个表时遇到问题,我得到的错误如下
无法在具有唯一索引“IX_AspNetUsers_RegistrarId”的对象“dbo.AspNetUsers”中插入重复的键行。重复键值为 (d75c86d4-32d8-4b34-8269-b31e3fd35d58)。该语句已终止。
在检查我的用户表的设计视图时,我看到了以下内容
CREATE UNIQUE NONCLUSTERED INDEX [IX_AspNetUsers_RegistrarId]
ON [dbo].[AspNetUsers]([RegistrarId] ASC)
WHERE ([RegistrarId] IS NOT NULL);
因此,在列上给出了一个唯一的约束,RegistrarId
但我找不到我在哪里添加了该条件/约束或在哪里/如何正确删除它。因此,我无法继续向数据库表中添加更多记录。
如果你能指导我如何纠正这个问题,请帮助我
谢谢