简体   繁体   English

实体框架查询outofmemoryexception

[英]Entity Framework query outofmemoryexception

I am new to the .NET Entity Framework and am trying iterate over the records in a table with several million rows. 我是.NET实体框架的新手,我正在尝试迭代数百万行的表中的记录。 Here is the basic code: 这是基本代码:

// select the records from the database
var records = from data in dataContext.Messages
                select data;

// iterate over the messages
foreach (var record in records)
{
    // do nothing
}

While iterating over the data I get an 'outofmemoryexception'. 在迭代数据时,我得到了“outofmemoryexception”。 Is there some way that I can alter my query or manage the memory of the ObjectQuery instance? 有什么方法可以改变我的查询或管理ObjectQuery实例的内存?

I suspect the problem is that Entity Framework is trying to cache / track all this data in your object context, which eventually causes the OutOfMemory Exception if the data set is huge. 我怀疑问题是Entity Framework正在尝试缓存/跟踪对象上下文中的所有这些数据,如果数据集很大,最终会导致OutOfMemory异常。

You can turn tracking off manually to avoid this: 您可以手动关闭跟踪以避免此问题:

dataContext.Messages.MergeOption = System.Data.Objects.MergeOption.NoTracking;

The memory allocated that you are currently seeing is within the data context - this memory will eventually get garbage collected once you dispose the context, so alternatively you could materialize smaller batches of rows inside a using block or manually dispose the object context to reclaim the memory between each batch. 您当前看到的内存分配在数据上下文中 - 一旦您处置了上下文,这个内存最终会被垃圾收集,因此您可以在使用块内实现较小批量的行或手动处理对象上下文以回收内存每批之间。

As for altering your query you can add a where clause to pare down records coming back: 至于更改查询,可以添加where子句来减少返回的记录:

http://msdn.microsoft.com/en-us/library/bb311043.aspx http://msdn.microsoft.com/en-us/library/bb311043.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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