实体框架急切地加载层次结构

时间:2018-06-18 07:20:10

标签: c# entity-framework

有没有人有改进此代码的想法。我有一个数据库,其中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);
 }

1 个答案:

答案 0 :(得分:0)

首先要提高可读性,我会强烈地在每个.之后打破一个新行(我无法真正阅读你的版本)。例如:

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)
{
.
.
.

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

最后一件事(对我来说没有多大意义),你可以在自定义扩展方法中对常见Then(..)命令进行分组(再次,对于这个例子,它没有意义)。

我相信没有什么可以改进的了。