c# - 实体框架急切地加载层次结构
问题描述
有没有人有改进此代码的想法。我有一个数据库,其中有 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);
}
解决方案
首先为了提高可读性,我会在每个之后强烈换行.
(我无法真正阅读你的版本)。例如:
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)
{
.
.
.
我可能还会使用Include
andThenInclude
与 lambda 表达式重载。如果您稍后重命名任何子属性,这将使您的生活更轻松(当您使用 lambda 表达式语法时,Visual Studio 将为您完成这项工作)。
最后一件事(这对我来说没有多大意义),您可以Then(..)
在自定义扩展方法中对常用命令进行分组(同样,对于本示例,它没有意义)。
我相信没有什么需要改进的了。
推荐阅读
- java - 当类中包含开关时,“插入'ClassBody'以完成ClassDeclaration”
- mariadb - 多主服务器的 Galera 集群:第二个节点无法在 Ubuntu 16.04.4 x64 中启动
- python - Pandas loc 仅适用于对象类型
- python - Pyping 安装错误
- r - 使用 Linux Mint 获取最新版本的 R
- android - 在 json 中使用 HTML 颜色标签
- javascript - JavaScript 中的函数式组合
- opencv - OpenCV Mat 到 Id2d1Bitmap
- eclipselink - 用于版本控制和乐观锁定的 JPA 2.1 时间戳类型字段总是抛出 OptimisticLockException
- laravel - laravel phpunit 测试期望状态码 201 但收到 302?