【问题标题】:Unable to load related data - is my configuration wrong?无法加载相关数据 - 我的配置是否错误?
【发布时间】:2020-04-21 03:35:16
【问题描述】:

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

这是我为Group 配置的OnModelCreating()(我没有为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();

注意GroupAdminnull,而GroupAdminId 有一个值。

【问题讨论】:

    标签: c# asp.net-core entity-framework-core ef-code-first relational-database


    【解决方案1】:

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

    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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-02
      • 2013-08-12
      • 1970-01-01
      • 1970-01-01
      • 2019-10-24
      • 2017-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多