首页 > 解决方案 > 实体框架急切地加载层次结构

问题描述

有没有人有改进此代码的想法。我有一个数据库,其中有 6 个表设置为层次结构:(tblLines.tblGroups.tblStations.tblDevices.tblSubDevices.tblSubSubDevices)

这段代码似乎有点重复,我需要一个更好的方法来做到这一点:

object NewItems = null;
if (ChildEntity is tblLine)
{
    NewItems = DBContext.tblLines.Include("tblGroups.tblStations.tblDevices.tblSubDevices.tblSubSubDevices").AsNoTracking().Single(x => x.ID == ((TblBase)ChildEntity).ID);  
 }
 if (ChildEntity is tblGroup)
 {
    NewItems = DBContext.tblGroups.Include("tblStations.tblDevices.tblSubDevices.tblSubSubDevices").AsNoTracking().Single(x => x.ID == ((TblBase)ChildEntity).ID);
 }
 if (ChildEntity is tblStation)
 {
    NewItems = DBContext.tblStations.Include("tblDevices.tblSubDevices.tblSubSubDevices").AsNoTracking().Single(x => x.ID == ((TblBase)ChildEntity).ID);
 }
 if (ChildEntity is tblDevice)
 {
    NewItems = DBContext.tblDevices.Include("tblSubDevices.tblSubSubDevices").AsNoTracking().Single(x => x.ID == ((TblBase)ChildEntity).ID);
 }
 if (ChildEntity is tblSubDevice)
 {
    NewItems = DBContext.tblSubDevices.Include("tblSubSubDevices").AsNoTracking().Single(x => x.ID == ((TblBase)ChildEntity).ID);
 }
 if (ChildEntity is tblSubSubDevice)
 {
    NewItems = DBContext.tblSubSubDevices.AsNoTracking().Single(x => x.ID == ((TblBase)ChildEntity).ID);
 }

标签: c#entity-framework

解决方案


首先为了提高可读性,我会在每个之后强烈换行.(我无法真正阅读你的版本)。例如:

object NewItems = null;
if (ChildEntity is tblLine)
{
    NewItems = DBContext
        .tblLines
        .Include("tblGroups.tblStations.tblDevices.tblSubDevices.tblSubSubDevices")
        .AsNoTracking()
        .Single(x => x.ID == ((TblBase)ChildEntity).ID);  
}
if (ChildEntity is tblGroup)
{
.
.
.

我可能还会使用IncludeandThenInclude与 lambda 表达式重载。如果您稍后重命名任何子属性,这将使您的生活更轻松(当您使用 lambda 表达式语法时,Visual Studio 将为您完成这项工作)。

最后一件事(这对我来说没有多大意义),您可以Then(..)在自定义扩展方法中对常用命令进行分组(同样,对于本示例,它没有意义)。

我相信没有什么需要改进的了。


推荐阅读