_
public class StructureEntity : EmEntityBase
{
[ForeignKey("ParentStructureId")]
public virtual StructureEntity ParentStructure { get; set; }
public long? ParentStructureId { get; set; }
[ForeignKey("SiteId")]
public virtual SiteEntity Site { get; set; }
[Required(ErrorMessage = "Required.")]
public long SiteId { get; set; }
[Required(ErrorMessage = "Required.")]
public string Name { get; set; }
}
public class SiteEntity : EmEntityBase
{
[ForeignKey("ParentSiteId")]
public virtual SiteEntity ParentSite { get; set; }
public long? ParentSiteId { get; set; }
[Required(ErrorMessage = "Required.")]
public long ClientId { get; set; }
[ForeignKey("ClientId")]
public ClientEntity Client { get; set; }
[Required(ErrorMessage = "Required.")]
public string Name { get; set; }
}
public class ClientEntity : EmEntityBase
{
public long? ParentClientId { get; set; }
[ForeignKey("ParentClientId")]
public virtual ClientEntity ParentClient { get; set; }
public string Name { get; set; }
}
现在,当我想急切加载所有引用的实体时。要做到这一点,我有:
public IQueryable<StructureDivisionEntity> GetAllWithInclude()
{
return GetAll()
.Include(e => e.Structure)
.Include(e => e.ParentStructureDivision.Structure)
.Include(e => e.Structure.Site.Client);
}
我想知道是否有一种动态的方法可以做到这一点,而无需明确地执行.Include(Structure)等。有类似的事情:
MyEntity.IncludeAllReferenced()其中IncludeAllReferenced使用反射或类似物来遍历MyEntity并执行所有包含?
更新:查询复杂图表的替代方法
答案 0 :(得分:0)
你不能这样做,但你可以做一个扩展方法来获得所有。 这可能是一个疯狂的想法,但您可以创建一个通用的扩展方法来处理所有类型,以使代码更加干净。
示例,(如果需要,可以使用工厂模式对其进行扩展):
public static IQueryable<T> IncludeAll<T>(this IQueryable<T> query)
{
if (typeof(T) == typeof(StructureDivisionEntity))
{
return GetAllWithInclude(query);
}
throw new NotImplementedException("IncludeAll not implemented for type {0}",typeof(T).FullName);
}
private static IQueryable<StructureDivisionEntity> GetAllWithInclude<StructureDivisionEntity> (IQueryable<StructureDivisionEntity> query)
{
return query.Include(e => e.Structure)
.Include(e => e.ParentStructureDivision.Structure)
.Include(e => e.Structure.Site.Client);
}