如果我在.tolist()之前执行.Select,实体框架将对DB执行附加查询

时间:2013-11-13 00:13:12

标签: asp.net-mvc linq asp.net-mvc-4 entity-framework-4

我有以下Action方法: -

public ActionResult RackServer(int id) {
            var servers = repository.AllFindRack_Servers(id).ToList();
            var IT360IDs = servers.Select(a => a.Technology.IT360ID.Value).ToArray();

            return PartialView("~/Views/Server/_nonPagedServerTable.cshtml", servers);

        }

调用以下存储库方法: -

public IQueryable<TMSServer> AllFindRack_Servers(int id)
        {



            return tms.TMSServers.Where(c => c.RackID == id)
            .Include(a => a.OperatingSystem)

            .Include(a3 => a3.TMSRack.DataCenter)
            .Include(a14 => a14.TMSRack.Technology)

            .Include(a6 => a6.TMSVirtualMachines)
            .Include(a7 => a7.TechnologyStatu)
            .Include(a8 => a8.TechnologyBackUpStatu)
            .Include(a9 => a9.TechnologyRole)
            .Include(a10 => a10.Technology.TechnologyIPs)
            .Include(a11 => a11.TMSServer1.Technology)
            .Include(a14=>a14.TMSServers1)
            .Include(a12 => a12.TMSSwitches)
            .Include(a13 => a13.TMSFirewalls);

        }

但我已经注意到,如果我在我的动作方法中将.Tolist()位置设置为: -

public ActionResult RackServer(int id) {
                var servers = repository.AllFindRack_Servers(id);
                var IT360IDs = servers.Select(a => a.Technology.IT360ID.Value).Tolist().ToArray();

                return PartialView("~/Views/Server/_nonPagedServerTable.cshtml", servers);

            }

然后将对存储库方法进行两次查询?任何人都可以解释为什么有。选择&amp;同一语句中的.Tolist()导致两个类似的quires被执行。?

由于

2 个答案:

答案 0 :(得分:0)

它正在进行延迟加载。关闭延迟加载并使用“include”代替:“。include(”tablename“)”

包括在sql语句中作为连接工作

关闭lazyloading:Disable lazy loading by default in Entity Framework 4

答案 1 :(得分:0)

在您的存储库中,您正在构建您正在利用延迟执行的查询

你的第一个查询就会触发

 var IT360IDs = servers.Select(a => a.Technology.IT360ID.Value).Tolist().ToArray();

这句话

第二次查询

 return PartialView("~/Views/Server/_nonPagedServerTable.cshtml", servers); 
 //as here you are accessing servers object

您必须将服务器替换为 IT360ID ......