You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core 6中为IdentityUser关联更多表的问题排查

问题:基于IdentityUser扩展用户表后,关联的子表属性始终返回null

现有基础实现

我已基于IdentityUser实现登录功能,自定义了关联AspNetUsers表的CoreUser类:

public class CoreUser: IdentityUser<string>
{
    public User User { get; set; }
}

关联需求与POCO类配置

我希望通过UserManager调用用户关联的更多数据表,目前尝试关联Registrations表与User表:

  • User表包含指向Registration表的外键RegistrationId,关联Registration表
  • Registration表还需关联VerificationAgency表

已在POCO类中定义关联:

User类代码

[Required]
[Display(Name = "Registration ID")]
[ForeignKey("RegistrationId")]
public System.Guid RegistrationId { get; set; }
public virtual Registration Registration { get; set; }

Registration类代码

public ICollection<User> Users { get; set; }
public ICollection<VerificationAgency> Verifications { get; set; }

问题现象

Registration及其关联的Verifications属性始终返回null。

当前配置与查询代码

OnModelCreating配置

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

    modelBuilder.Entity<CoreUser>()
            .HasOne(a => a.User)
            .WithOne()
            .HasForeignKey<User>(a => a.AspNetUsersId)
            .OnDelete(DeleteBehavior.Cascade);

    modelBuilder.Entity<CoreRole>();

        //自动注册所有实现IEntityTypeConfiguration的配置类
    modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
}

登录用户查询代码

private User _loggedInUser;

protected User LoggedInUser
{
    get
    {
        if (_loggedInUser == null)
        {
            var userWhere = _userManager.Users
                                        .Where(x => x.UserName == User.Identity.Name);

            _loggedInUser = userWhere.Select(user => user.User)
                                     .Include(x => x.Registration)
                                     .Include(x => x.Registration.Verifications)
                                     .FirstOrDefault();
        }

        return _loggedInUser;
    }
}

已尝试的Registration映射配置

builder.HasMany(x => x.Users)
       .WithOne(x => x.Registration)
       .HasForeignKey(x => x.RegistrationId);

builder.HasMany(x => x.Verifications)
       .WithOne(x => x.Registration)
       .HasForeignKey(x => x.RegistrationId);

请问是否遗漏了映射配置,或者无法为用户表关联额外数据表?(附数据库结构截图:User表含RegistrationId外键,Registration表与VerificationAgency表存在关联)


内容的提问来源于stack exchange,提问作者Mohammed Ismail

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 10:07:35