EF 包含,然后包含



我有几个模型正在尝试与 Include 绑定,它不会返回所有预期的相关数据。 完整的链是:

用户(一个(>角色(一个(>权限(多个(>实体(一个(> 实体区域(一个(

这些是我的模型:(CompanyBase 是一个带有 companyId 的基类(

public class User : _CompanyBase
{
public int UserID { get; set; }
public string FullName { get; set; }
public int RoleID { get; set; }
public Role Role { get; set; }
}

public class Role : _CompanyBase
{
[Key, Column(Order = 1), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int RoleID { get; set; }
[Required]
[StringLength(100, MinimumLength = 3)]
public string Name { get; set; }
public ICollection<RolePermission> RolePermissions { get; set; }
public ICollection<User> Users { get; set; }
}

public class RolePermission : _CompanyBase
{
[Key, Column(Order = 1), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int RolePermissionID { get; set; }
public Guid Id { get; set; }
[Required]
[StringLength(100, MinimumLength = 3)]
public string PermissionCode { get; set; }

public int RoleID { get; set; }
public Role Role { get; set; }

public int EntityID { get; set; }
public Entity Entity { get; set; }

}
public class Entity : _CompanyBase
{
[Key, Column(Order = 1), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int EntityID { get; set; }
[Required]
[StringLength(100, MinimumLength = 3)]
public string DisplayName { get; set; }

public int EntityAreaID { get; set; }
public EntityArea EntityArea { get; set; }

}
public class EntityArea :_CompanyBase
{
[Key, Column(Order = 1), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int EntityAreaID { get; set; }
[Required]
[StringLength(50, MinimumLength = 3)]
public string Name { get; set; }

public ICollection<Entity> Entities { get; set; }
}

我试图将它们绑定:

dbUser = db.Users
.AsNoTracking()
.Where(x => x.UserId == UserID)
.Include(m => m.Role)
.ThenInclude(m => m.RolePermissions)
.ThenInclude(m => m.Entity)
.ThenInclude(m => m.EntityArea)
.FirstOrDefault();

但是,我确实获得了角色,但我没有得到任何进一步的信息(角色权限集合、实体和区域(。 我从根本上做错了什么吗? 这是一个只读查询,因此不使用跟踪。

谢谢!

我认为你的尝试没有任何根本性的问题。您是否检查过特定用户在连接的表中是否确实有任何数据?

当你不需要它时,Include(( 有时会生成一个左连接,所以我建议你尽可能远离它。我通常会使用投影来指定我想要接收的数据。对于您的示例,这可以通过以下方式完成:

dbUser = db.Users
.AsNoTracking()
.Where(x => x.UserId == UserID)
.Select(x => new 
{
Role = x.Role,
RolePermissions = x.RolePermissions,
Entity = x.Entity,
EntityArea = x.EntityArea
})
.FirstOrDefault();

相关内容

最新更新