无法加载相关数据-我的配置是否错误?

问题描述 投票:0回答:1

我有一个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();

enter image description here

注意GroupAdmin如何为null,而GroupAdminId具有值。

c# asp.net-core entity-framework-core ef-code-first relational-database
1个回答
0
投票

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

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
}
© www.soinside.com 2019 - 2024. All rights reserved.