C# 为什么Asp.net核心标识中的UserRoles中有两个额外的列?
据 自定义用户C# 为什么Asp.net核心标识中的UserRoles中有两个额外的列?,c#,asp.net,asp.net-core,identity,C#,Asp.net,Asp.net Core,Identity,据 自定义用户 public class AppUser : IdentityUser { public string FirstName { get; set; } public string LastName { get; set; } public virtual ICollection<AppUserRole> UserRoles { get; set; } } 公共类AppUser:IdentityUser { 公共字符串名{get;set;}
public class AppUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<AppUserRole> UserRoles { get; set; }
}
公共类AppUser:IdentityUser
{
公共字符串名{get;set;}
公共字符串LastName{get;set;}
公共虚拟ICollection用户角色{get;set;}
}
自定义角色:
public class AppRole : IdentityRole
{
AppRole() { }
public AppRole(string name) : base(name)
{
Id = Guid.NewGuid().ToString();
}
public virtual ICollection<AppUserRole> UserRoles { get; set; }
public virtual ICollection<AppRoleClaim> RoleClaims { get; set; }
}
公共类许可证:IdentityRole
{
近似(){}
公共许可(字符串名称):基本(名称)
{
Id=Guid.NewGuid().ToString();
}
公共虚拟ICollection用户角色{get;set;}
公共虚拟IColleclaims{get;set;}
}
DbContext:
public class AppDbContext : IdentityDbContext<AppUser, AppRole, string,
IdentityUserClaim<string>, AppUserRole, IdentityUserLogin<string>,
IdentityRoleClaim<string>, IdentityUserToken<string>>
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
}
公共类AppDbContext:IdentityDbContext
{
公共AppDbContext(DbContextOptions选项)
:基本(选项)
{
}
}
但是在AspNetUserRoles表中有四列!(RoleId,UserId,RoleId1,UserId1)这两个额外的列(UserId1和RoleId1)是由于这行代码。实际上,icollection在数据库中的表上创建索引。删除此项并运行迁移,希望额外的列将消失
从appuser和approle类中删除此
公共虚拟ICollection UserRoles{get;set;}
问题涉及在配置一对多关系时未指定外键,请尝试使用以下代码指定外键:
public class ApplicationDbContext
: IdentityDbContext<
ApplicationUser, ApplicationRole, string,
IdentityUserClaim<string>, ApplicationUserRole, IdentityUserLogin<string>,
IdentityRoleClaim<string>, IdentityUserToken<string>>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUser>(b =>
{
// 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();
});
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();
});
}
}
public类ApplicationDbContext
:IdentityDbContext<
ApplicationUser、ApplicationRole、string、,
IdentityUserClaim、ApplicationUserRole、IdentityUserLogin、,
IdentityRoleClaim,IdentityUserToken>
{
public ApplicationDbContext(DbContextOptions.Hi@RezaAhmadi,我可以知道回复是否解决了问题,或者该线程是否有任何更新吗?如果答案解决了问题,请接受它-请参阅。如果您对我的回复有任何疑问,请随时告诉我。