【问题标题】:Linq to Entities with Linq to XML running very slowlyLinq to Entity with Linq to XML 运行非常缓慢
【发布时间】:2016-04-28 17:04:00
【问题描述】:

我正在查询一个表,只是要求它返回一个值。然后用那个值构建 XML。当我在 SSMS 中运行查询时,返回的数据不到一秒钟。如果我在 VPN 上运行它,使用 Linq to Entitities 和 Linq to XML,我已经等了 30 分钟,最后退出了。有没有办法提高性能?

这是代码(我将一个供应商对象传递给此过程,它是供应商表中记录的表示):

using (Context ctx = new Context())
{
   XElement xe = new XElement("Orders",
      from o in ctx.Orders.ToList()
      where (o.VendorID.Equals(vendor.VendorID) && o.OrderStateID.Equals(3))
      select
         new XElement("Order",
         new XElement("OrderNumber", o.OrderID)));
}         

【问题讨论】:

  • ToListWhere 之前?这不是 LINQ to Entities,您将整个表放入内存并运行 LINQ to Objects 查询。

标签: entity-framework linq linq-to-entities linq-to-xml


【解决方案1】:

最好在数据库中执行过滤,而不是读取内存中的整个表并执行 LINQ to Objects 查询(实际上您可以通过 ToList 调用 ctx.Orders 来执行此操作)。

   XElement xe = new XElement("Orders",
      from o in (from o in ctx.Orders
                 where o.VendorID.Equals(vendor.VendorID) && o.OrderStateID.Equals(3)
                 select new { o.OrderID } // Select just the fields needed
                 ).AsEnumerable() // Switch to LINQ to Objects
      select
         new XElement("Order",
         new XElement("OrderNumber", o.OrderID)));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 2020-02-21
    • 2010-12-06
    相关资源
    最近更新 更多