如何在 ASP.NET Core 5 中使用 IdentityUser 和 IdentityRole 之间的隐式多对多

2024-04-08

我有这两个实体。

public class ApplicationUser : IdentityUser<int>
    {
        public int DepartmentId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string NationalCode { get; set; }
        public DateTimeOffset DateCreated { get; set; } = DateTimeOffset.Now;
        public DateTimeOffset DateModified { get; set; } = DateTimeOffset.Now;
        public CorporateTitle CorporateTitle { get; set; }

        public Department Department { get; set; }
        public ICollection<ApplicationRole> Roles { get; set; } //* instead of IdetityUserRole

  public class ApplicationRole : IdentityRole<int>
    {
        public string DisplayName { get; set; }
        public string Description { get; set; }
        public ICollection<ApplicationUser> Users { get; set; } //* instead of IdetityUserRole

    }

我想自定义这两个实体,例如覆盖导航属性。 我不想将 IdentityUserRole 类用于这些类之间的多对多关系。

我应该如何在 Identity Core 中为这种类型的隐式多对多编写配置?

 builder.Entity<ApplicationUser>()
                .HasMany(appUser => appUser.Roles)
                .WithMany(role => role.Users)
                .UsingEntity<>(); // here I don't know how to config this relationship.

这是该场景的配置需求。 (跳过导航 EF Core 5)

 builder.Entity<ApplicationUser>()
                        .HasMany(u => u.Roles)
                        .WithMany(r => r.Users)
                        .UsingEntity<IdentityUserRole<int>>
                        (au => au.HasOne<ApplicationRole>().WithMany(role => role.UserRoles).HasForeignKey(u=> u.RoleId),
                        au => au.HasOne<ApplicationUser>().WithMany(user => user.UserRoles).HasForeignKey(r=> r.UserId));

完整的源代码:https://github.com/ArminShoeibi/ImplicitManyToManyIdentityCore https://github.com/ArminShoeibi/ImplicitManyToManyIdentityCore

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 ASP.NET Core 5 中使用 IdentityUser 和 IdentityRole 之间的隐式多对多 的相关文章

随机推荐