首页 > 解决方案 > 无法加载相关数据 - 我的配置是否错误?

问题描述

我有一个ApplicationUser和一个Group

public class ApplicationUser : IdentityUser
{
    public int? AdminInGroupId { get; set; }
    public int? UserInGroupId { get; set; }
    public Group AdminInGroup { get; set; }
    public Group UserInGroup { get; set; }
    // some more properties
}

public class Group
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string GroupAdminId { get; set; }
    public ApplicationUser GroupAdmin { get; set; }
    public List<ApplicationUser> GroupUsers { get; set; }
}

这是我的OnModelCreating()配置Group(我没有ApplicationUser):

modelBuilder.Entity<Group>()
    .HasOne(a => a.GroupAdmin)
    .WithOne(g => g.AdminInGroup)
    .HasForeignKey<ApplicationUser>(a => a.AdminInGroupId);

modelBuilder.Entity<Group>()
    .HasMany(u => u.GroupUsers)
    .WithOne(g => g.UserInGroup)
    .OnDelete(DeleteBehavior.NoAction);

运行下面的查询时,我没有得到GroupAdmin

Group group = await db.Groups
    .Include(a => a.GroupAdmin)
    .Include(u => u.GroupUsers)
    .Where(m => m.Id == id)
    .FirstOrDefaultAsync();

在此处输入图像描述

注意GroupAdminis null, whileGroupAdminId有一个值。

标签: c#asp.net-coreentity-framework-coreef-code-firstrelational-database

解决方案


我无法理解您的数据库设计,为什么您在一张表中有一对一和一对多的关系。请检查我的代码可能更适合您的项目。

public class ApplicationUser : IdentityUser
{
    public int? GroupId { get; set; }
    public Group Group { get; set; }
    // some more properties
}

public class Group
{
    public int Id { get; set; }
    public string Name { get; set; }
    public GroupType GroupType { get; set; }
    public List<ApplicationUser> Users { get; set; }
}
public enum GroupType
{ 
 AdminGroup = 0 ,
 UserGroup = 1 ,
 BothGroup = 2
}

推荐阅读