【问题标题】:How to use Implicit Many to Many between IdentityUser and IdentityRole in ASP.NET Core 5如何在 ASP.NET Core 5 中的 IdentityUser 和 IdentityRole 之间使用隐式多对多
【发布时间】:2021-04-27 17:32:12
【问题描述】:

我有这两个实体。

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

    }

我想自定义这 2 个实体,例如覆盖导航属性。 我不想将 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.

【问题讨论】:

  • 如果您喜欢或不喜欢,没有 IdentityUserRole 表就无法管理。 EF 将为您创建此表,可能只是名称不同。但是如果你控制它并了解它是如何工作的,它会更好。
  • 感谢您的回答,但我知道如何使用 asp.net core 2 和 3 中的该表,我想在不使用 UserManager 类的情况下查询角色和用户,因此我想查询更简单这两张桌子之间。
  • 没关系,因为 Net5 在任何情况下都会创建这个表。如果您以正确的方式配置导航属性,则对于您的查询,您不需要使用第三个表。您将拥有自己喜欢的 public ICollection Roles { get;放; } 在这种情况下。仅当您不使用主键和外键时,才需要在查询中使用第三个表。这样您就可以手动进行所有连接。
  • 谢谢,但我是个老学生,我更喜欢控制一切。如果你真的想了解这些东西是如何工作的,你可以在这里查看我的答案stackoverflow.com/questions/65706128/…。如果有帮助别忘了点赞。
  • 但我现在明白你的意思了。你给了我一些思考的食物。谢谢,我今天会尝试另一种方式。

标签: c# many-to-many asp.net-core-5.0 ef-core-5.0


【解决方案1】:

这是此场景的配置需求。 (跳过导航 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多