[英]Entity framework eagerly load hierarchy
有沒有人有改進此代碼的想法。 我有一個以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)
{
.
.
.
我可能還會在lambda表達式重載中使用Include
和ThenInclude
。 如果以后重命名任何子屬性,將使您的工作變得更加輕松(當您使用lambda表達式語法時,Visual Studio會為您完成此工作)。
最后一件事(這對我來說沒有太大意義),您可以將常用的Then(..)
命令分組到一個自定義擴展方法中(同樣,對於本示例來說,這沒有意義)。
我相信沒有其他需要改進的地方。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.