title: EF6 OutOfMemoryException Evaluating Entity with varbinary(max) Property
body: <p>In my WebAPI web app, I've added a varbinary(max) field to a table, and a byte[] field to the POCO (BatchCharge). This entity has a child entity (Charge). </p>
  
  <p>Visual Studio 2013, Entity Framework 6, SQL Server 2014.</p>
  
  <p>The data model is as follows:</p>
  
  <pre><code>public class BatchCharge
  {
      public int ID { get; set; }
      public byte[] FileData { get; set; }
      public virtual ICollection&lt;Charge&gt; Charges { get; set; } 
  }
  
  public class Charge
  {
      public int ID { get; set; }
      public DateTime CreatedUTC { get; set; }
      public decimal Amount { get; set; }
      public virtual BatchCharge BatchCharge { get; set; }
  }
  </code></pre>
  
  <p>The mapping is done on the Charge entity (child) as follows:</p>
  
  <pre><code>public class ChargeMap : EntityTypeConfiguration&lt;Charge&gt;
  {
      public ChargeMap()
      {
          // Primary Key
          HasKey(t =&gt; t.ID);
  
          // Table and Column Mappings
          ToTable("Charge");
          Property(t =&gt; t.ID).HasColumnName("ID");
          Property(t =&gt; t.ID).IsRequired();
  
          Property(t =&gt; t.CreatedUTC).HasColumnName("CreatedUTC");
          Property(t =&gt; t.CreatedUTC).IsRequired();
  
          Property(t =&gt; t.Amount).HasColumnName("Amount");
          Property(t =&gt; t.Amount).IsRequired();
  
          HasRequired(t =&gt; t.BatchCharge)
              .WithMany(t =&gt; t.Charges)
              .HasForeignKey(d =&gt; d.BatchChargeID);
      }
  }
  </code></pre>
  
  <p>When retrieving a list of BatchCharges using the method below:</p>
  
  <pre><code>    [ActionName("GetBatchCharges")]
      [HttpGet]
      [Route("api/charges/batches")]
      [Authorize(Roles = "Administrator")]
      public HttpResponseMessage GetBatchCharges(int skip = 0,
          int take = 25,
          int statusFilter = 0)
      {
          try
          {
              var batchCharges = _centralDb.BatchCharges.AsQueryable();
              if (statusFilter &gt; 0)
              {
                  batchCharges = batchCharges.Where(bc =&gt; bc.StatusID == statusFilter);
              }
  
              // Page and list.
              var allBatchCharges = batchCharges.OrderByDescending(c =&gt; c.CreatedUTC);
              var totalCount = allBatchCharges.Count();
              var thePage = allBatchCharges.Skip(take * skip).Take(take).ToList();
  
              // Transform and return.
              var result = new
              {
                  TotalCount = totalCount,
                  CurrentPage = skip,
                  BatchCharges = thePage.Select(c =&gt; MapperFactory.Mapper.Map&lt;BatchCharge, BatchChargeDTO&gt;(c)).ToList()
              };
              return Request.CreateResponse(HttpStatusCode.OK, result);
          }
          catch (Exception ex)
          {
              const string message = "Exception getting batch charges.";
              Logger.Error(ex, message);
              return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, new HttpError(message));
          }
      }
  </code></pre>
  
  <p>I get an OutOfMemoryException. When I break on the line above and try to view the query results, I see instead the error "The function evaluation was disabled because of an out of memory exception.". See screenshot below.</p>
  
  <p><a href="https://i.stack.imgur.com/YU9b0.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/YU9b0.jpg" alt="Debugger view after evaluating Linq"></a></p>
  
  <p>This tells me the out of memory exception is occurring inside EF6.</p>
  
  <p>I've seen several related answers about how to increase process memory. I don't believe this is the problem. The test data includes six rows in the BatchCharge (parent) table, and a max file size of 27 KB!</p>
  
  <p>The file is a CSV file with the child entity (Charges) information. I have no problem uploading and saving BatchCharges with file data using this model. I've also used it successfully on small numbers of Charges (child entities) per BatchCharge.</p>
  
  <p>The problem started when I uploaded a BatchCharge with 600 Charges as children. As I mentioned, it's not a file size issue, because the file size is 27KB.</p>
  
  <p>If there is a circular reference here, it should happen in many other similarly configured relationships I have. Or is the byte array field creating the problem in conjunction with the parent/child relationship? If so, how? </p>
  
  <p><strong>EDIT:</strong>
  When I surround the code with a try/catch block, and run it step by step in a debugger, it doesn't throw an exception anywhere in my code! However, the response that reaches the browser includes a standard IIS unhandled exception page, with a server error as follows (run the snippet to see output):</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
  <div class="snippet-code">
  <pre class="snippet-code-css lang-css prettyprint-override"><code>         body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} 
           p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
           b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
           H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
           H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
           pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
           .marker {font-weight: bold; color: black;text-decoration: none;}
           .version {color: gray;}
           .error {margin-bottom: 10px;}
           .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
           @media screen and (max-width: 639px) {
            pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
           }
           @media screen and (max-width: 479px) {
            pre { width: 280px; }
           }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>    &lt;body bgcolor="white"&gt;
  
              &lt;span&gt;&lt;H1&gt;Server Error in '/' Application.&lt;hr width=100% size=1 color=silver&gt;&lt;/H1&gt;
  
              &lt;h2&gt; &lt;i&gt;Exception of type 'System.OutOfMemoryException' was thrown.&lt;/i&gt; &lt;/h2&gt;&lt;/span&gt;
  
              &lt;font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif "&gt;
  
              &lt;b&gt; Description: &lt;/b&gt;An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
  
              &lt;br&gt;&lt;br&gt;
  
              &lt;b&gt; Exception Details: &lt;/b&gt;System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.&lt;br&gt;&lt;br&gt;
  
              &lt;b&gt;Source Error:&lt;/b&gt; &lt;br&gt;&lt;br&gt;
  
              &lt;table width=100% bgcolor="#ffffcc"&gt;
                 &lt;tr&gt;
                    &lt;td&gt;
                        &lt;code&gt;
  
  An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.&lt;/code&gt;
  
                    &lt;/td&gt;
                 &lt;/tr&gt;
              &lt;/table&gt;
  
              &lt;br&gt;
  
              &lt;b&gt;Stack Trace:&lt;/b&gt; &lt;br&gt;&lt;br&gt;
  
              &lt;table width=100% bgcolor="#ffffcc"&gt;
                 &lt;tr&gt;
                    &lt;td&gt;
                        &lt;code&gt;&lt;pre&gt;
  
  [OutOfMemoryException: Exception of type &amp;#39;System.OutOfMemoryException&amp;#39; was thrown.]
     System.IO.MemoryStream.set_Capacity(Int32 value) +89
     System.IO.MemoryStream.EnsureCapacity(Int32 value) +90
     System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count) +326
     Microsoft.VisualStudio.Web.PageInspector.Runtime.Tracing.ArteryFilter.Write(Byte[] buffer, Int32 offset, Int32 count) +106
     System.Web.HttpWriter.FilterIntegrated(Boolean finalFiltering, IIS7WorkerRequest wr) +475
     System.Web.HttpResponse.FilterOutput() +154
     System.Web.CallFilterExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80
     System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +247
     System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp;amp; completedSynchronously) +117
  &lt;/pre&gt;&lt;/code&gt;
  
                    &lt;/td&gt;
                 &lt;/tr&gt;
              &lt;/table&gt;
  
              &lt;br&gt;
  
              &lt;hr width=100% size=1 color=silver&gt;
  
              &lt;b&gt;Version Information:&lt;/b&gt;&amp;nbsp;Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.3056.0
  
              &lt;/font&gt;
  
      &lt;/body&gt;</code></pre>
  </div>
  </div>
  </p>