EF Core 2.0标识 - 添加导航属性

时间:2017-08-24 13:55:21

标签: c# mysql postgresql entity-framework-core

在EF Core 2.0中,默认情况下不包含身份导航属性,因此在升级后,我添加了它们。因此,对于用户和角色之间的多对多关系,以及Role和RoleClaim之间的一对多关系,我添加了以下导航属性:

public class User : IdentityUser
{
    [Required]
    public string Name { get; set; }

    public virtual ICollection<IdentityUserRole<string>> Roles { get; set; }
}

public class Role : IdentityRole
{
    [Required]
    public string Name { get; set; }

    public virtual ICollection<IdentityRoleClaim<string>> Claims { get; set;}
}

令人惊讶的是,它为RoleId1表和AspNetRoleClaimsUserId1表添加了额外的AspNetUserRoles密钥,并且所有获取查询实际上都使用新密钥而不是RoleIdUserId也存在。

3 个答案:

答案 0 :(得分:4)

我不知道为什么,没有这些有用的导航属性。我想列出具有角色的用户。

所以我做了以下事情:

public class ApplicationUser : IdentityUser
{
    public virtual ICollection<ApplicationUserRole> UserRoles { get; } = new List<ApplicationUserRole>();
}

public class ApplicationUserRole : IdentityUserRole<string>
{
    public virtual ApplicationUser User { get; set; }
    public virtual ApplicationRole Role { get; set; }
}

public class ApplicationRole : IdentityRole<string>
{
    public ApplicationRole(){ }

    public ApplicationRole(string roleName)
        : base(roleName)
    {
    }

    public virtual ICollection<ApplicationUserRole> UserRoles { get; } = new List<ApplicationUserRole>();
}

这会创建导航,但会创建其他列,例如RoleId1Discriminator。所以,我根据Add IdentityUser POCO Navigation Properties添加了以下内容。

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    builder.Entity<ApplicationUser>()
        .HasMany(e => e.UserRoles)
        .WithOne()
        .HasForeignKey(e => e.UserId)
        .IsRequired()
        .OnDelete(DeleteBehavior.Cascade);

    builder.Entity<ApplicationUserRole>()
        .HasOne(e => e.User)
        .WithMany(e => e.UserRoles)
        .HasForeignKey(e => e.UserId);

    builder.Entity<ApplicationUserRole>()
        .HasOne(e => e.Role)
        .WithMany(e => e.UserRoles)
        .HasForeignKey(e => e.RoleId);
}

但我仍然有RoleId1Discriminator两列。之后,我用ApplicationDbContext,DI配置服务和DB种子中的新ApplicationRole类替换。

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserClaim<string>
    , ApplicationUserRole, IdentityUserLogin<string>, IdentityRoleClaim<string>, IdentityUserToken<string>>
{
    ...
}

public void ConfigureServices(IServiceCollection services)
{
   ...
   services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();
   ...
}

public DbInitializer(
        ApplicationDbContext context,
        UserManager<ApplicationUser> userManager,
        RoleManager<ApplicationRole> roleManager)
    {
        _context = context;
        _userManager = userManager;
        _roleManager = roleManager;
    }

public async void Initialize()
    {
        _context.Database.EnsureCreated();

        if (!_context.Roles.Any(r => r.Name == SharedConstants.Role.ADMINISTRATOR))
            await _roleManager.CreateAsync(new ApplicationRole(SharedConstants.Role.ADMINISTRATOR));
    }            

另外,我可以导航并获得角色的名字。

ctx.Users.Select(e => new
            {
                e.Id,
                e.UserName,
                e.Email,
                e.PhoneNumber,
                Roles = e.UserRoles.Select(i => i.Role.Name).ToList()
            }).ToList();

我希望这能为您提供Claims导航属性的线索。

答案 1 :(得分:0)

我遇到了同样的问题,这是解决方案。

您必须告诉Ef您将在哪个导航属性上拥有OneToMany Relation。

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);


        CreateUserModel(modelBuilder.Entity<User>());
        CreateRoleModel(modelBuilder.Entity<Role>());

    }


    private void CreateRoleModel(EntityTypeBuilder<Role> entityTypeBuilder)
    {
        entityTypeBuilder.HasMany(role => role.UserRoles).
            WithOne(**e=> e.Role**).
            HasForeignKey(userRole => userRole.RoleId).
            IsRequired()
            .OnDelete(DeleteBehavior.Cascade);
    }

    private void CreateUserModel(EntityTypeBuilder<User> entityTypeBuilder)
    {
        entityTypeBuilder.HasMany(user => user.UserRoles).
            WithOne(**e=>e.User**).
            HasForeignKey(userRole => userRole.UserId).
            IsRequired()
            .OnDelete(DeleteBehavior.Cascade);
    }

您还可以在字符串中指定导航属性,例如

private void CreateRoleModel(EntityTypeBuilder<Role> entityTypeBuilder)
    {
        entityTypeBuilder.HasMany(role => role.UserRoles).
            WithOne(**"Role"**).
            HasForeignKey(userRole => userRole.RoleId).
            IsRequired()
            .OnDelete(DeleteBehavior.Cascade);
    }

    private void CreateUserModel(EntityTypeBuilder<User> entityTypeBuilder)
    {
        entityTypeBuilder.HasMany(user => user.UserRoles).
            WithOne(**"User"**).
            HasForeignKey(userRole => userRole.UserId).
            IsRequired()
            .OnDelete(DeleteBehavior.Cascade);
    }

答案 2 :(得分:0)

我也遇到过同样的情况。在我的情况下,问题是由于我将调用放在OnModelCreating底部的base.OnModelCreating(builder)上引起的。最顶部移动base.OnModelCreating(builder)解决了该问题(没有重复的列和FK)。

enter image description here

感谢此GutHub issue