c# - 无法加载相关数据 - 我的配置是否错误?
问题描述
我有一个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();
注意GroupAdmin
is null
, whileGroupAdminId
有一个值。
解决方案
我无法理解您的数据库设计,为什么您在一张表中有一对一和一对多的关系。请检查我的代码可能更适合您的项目。
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
}
推荐阅读
- python - 广度优先搜索:如何获得货币兑换?
- c# - 在 C# 中打印或预览时如何更改 AdvanceDGV 的方向
- flutter - Flutter StreamBuilder 在加载时删除旧数据
- r - googleVis 不显示命令后的情节
- git - VSCode 编辑器作为 git 编辑器失败:无法连接到 VSCode 服务器
- python - 需要修复 ValueError: I/O operation on closed file
- c++ - 如何转储 Wireshark 的 IP 数据包缓冲区/如何在 C++ 中进行 hexdump?
- excel - 在Excel中除以
- java - Dialogflow 部署 JAVA 库
- c# - 如何让我的前进动作与相机的方向相匹配?