简体   繁体   中英

Entity framework eagerly load hierarchy

Does anyone have an idea for improving this code. I have a database with 6 tables setup as a hierarchy:(tblLines.tblGroups.tblStations.tblDevices.tblSubDevices.tblSubSubDevices)

This code seems a bit repetitive, and I need a better way to do this:

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);
 }

First to improve the readability, I would strongly break a new line after each . (I could not really read your version). For example:

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

I would probably also use Include and ThenInclude with lambda expression overload. It would make your life much easier if you later rename any of the sub properties (visual studio will do that job for you when you use lambda expression syntax).

Last thing (which does not make that much sense for me), you may group the common Then(..) commands in a custom extension method (again, for this example it does not make sense).

I believe there is nothing more to be improved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM