如何在lambda表达式中指定Include

时间:2013-07-24 13:40:10

标签: c# asp.net entity-framework

我有一个机架型号和一个服务器型号。目前,当我想要检索单个服务器时,我执行以下操作,以指定显式加载: -

public Server FindAllServer(int id)
        {

            return project.Servers.Where(c => c.ServerID == id)
                .Include(a => a.OperatingSystem)
                .Include(a2 => a2.DataCenter)
                .Include(a3=>a3.Rack)
                .Include(a4=>a4.ServerModel)
                .Include(a5=>a5.Technology)
                .Include(a6=>a6.VirtualMachines)
                .Include(a7=>a7.TechnologyStatu)
                .Include(a8=>a8.TechnologyBackUpStatu)
                .Include(a9=>a9.TechnologyRole)
                .SingleOrDefault();
        }

但是现在我想显示一个Rack及其所有服务器,我做了以下几点: -

 public Rack FindAllRack(int id)
        {

            return project.Racks.Where(c => c.RackID == id)
                .Include(a => a.Servers)
                .Include(a2 => a2.DataCenter)
                .Include(a3 => a3.Firewalls)
                .Include(a4 => a4.Routers)
                .Include(a5 => a5.Technology)
                .Include(a6 => a6.StorageDevices)
                .Include(a7=>a7.Switches)
                .Include(a8=>a8.Zone)
                .SingleOrDefault();
        }

所以我不确定如何定义明确包含Rack下Server的所有导航属性,因为我不能写出如下内容: -

project.Racks.Where(c => c.RackID == id).Include(a => a.Servers.Include(………))

问题是,如果我在一个机架下有50个服务器,那么对于每个服务器,将有大约7个请求来检索服务器导航属性,所以我将有大约350个请求!

3 个答案:

答案 0 :(得分:1)

我认为您应该能够通过指定属性路径(例如Include())来执行基于字符串的重载。

project.Racks.Where(c => c.RackID == id).Include("Servers.SomePropertyOfServer")

编辑:在做了更多研究后,看起来这也可行:

project.Racks.Where(c => c.RackID == id).Include(a => a.Servers.Select(s => s.SomePropertyOfServer))

请参阅this link,特别是标题为“热切加载多个级别”的部分。

答案 1 :(得分:1)

如果您需要的只是各种子对象的计数,请考虑以下内容。它应该向数据库发出单个请求,最多只能获取2行。描述请求以确保是这种情况,因为我还没有测试过。

        return project.Racks.Where(c => c.RackID == id)
            .Select(a => new {
                serverCount = a.Servers.Count(),
                dataCenterCount = a.DataCenter.Count(),
                firewallCount = a.Firewalls.Count(),
                routerCount = a.Routers.Count(),
                technologyCount = a.Technology.Count(),
                storageDeviceCount = a.StorageDevices.Count(),
                switchCount = a.Switches.Count(),
                zoneCount = a.Zone.Count()
            }).SingleOrDefault();

此外,如果您不打算在获得多条记录时抛出异常,请使用FirstOrDefault而不是SingleOrDefault。

答案 2 :(得分:0)

你试过这个吗?

return project.Servers
              .Include(a => a.OperatingSystem)
              .Include(a2 => a2.DataCenter)
              .Include(a3=>a3.Rack)
              .Include(a4=>a4.ServerModel)
              .Include(a5=>a5.Technology)
              .Include(a6=>a6.VirtualMachines)
              .Include(a7=>a7.TechnologyStatu)
              .Include(a8=>a8.TechnologyBackUpStatu)
              .Include(a9=>a9.TechnologyRole)
              .Where(srv => srv.Rack.RackID == id);