EntityFramework.dll中出现“System.OutOfMemoryException”类型的异常,但未在用户代码中处理

时间:2016-06-12 12:59:51

标签: c# asp.net entity-framework linq

我有这个功能

 public static List<Product> GetProductsByStoreID(int? StoreID, ProductLocation? location , string search = "", string barcode = "", string Relations = "no")
        {
            using (DbContext Context = new DbContext())
            {
                string Barcode = "";//.TrimStart('0');
                if (Barcode.IndexOf("d") == 0)
                {
                  Barcode=  barcode.Split('d')[1];
                }
                else
                {
                    Barcode = barcode;
                }
                IQueryable<Product> products = Context.Products.Include(p => p.PosOrderDetail);
                foreach (string item in GetRelations(Relations))
                {
                    products = products.Include(item);
                }

                if (!string.IsNullOrEmpty(Barcode))
                    products = products.Where(p => p.Barcode.Contains(Barcode));

                if (!string.IsNullOrWhiteSpace(search))
                    products = products.Where(p => p.Item.ItemName.Contains(search) || p.Description.Contains(search));
                if ( location != null)
                    products = products.Where(d => d.ProductLocation == (int)location);
                if (StoreID != null)
                    products = products.Where(d => d.StoreID == StoreID );

                if (products.Count() > 0)
                    return products.ToList();
                else
                    return null;
            }
        }

它在return products.ToList();

中给了我例外
  

发生了'System.OutOfMemoryException'类型的异常   EntityFramework.dll但未在用户代码中处理

数据非常庞大,因为当我使用其他属性进行过滤时 IQueryable<Product> products = Context.Products.Include(p => p.weight );

它工作正常 请帮忙

1 个答案:

答案 0 :(得分:1)

实体框架为变更跟踪保留了额外的数据副本, 如果你真的想要将非常大的数据集加载到内存中,请尝试使用&#34; AsNoTracking()&#34;加载数据。告诉EF不要保留第二份副本的选项

Context.products.AsNoTracking()。ToList()