Error while trying to download large file from database using Entity Framework

asp.net, c#, download, entity-framework

Solution

You need to increase the command timeout:

using (SFTDBEntities db = new SFTDBEntities())
{
    db.CommandTimeout = int.MaxValue; //For test

    Guid Id_LogServerLogFile = Guid.Parse(lblId.Text.Trim());
    LogServerLogFile logServerLogFile = new LogServerLogFile();
    logServerLogFile = db.LogServerLogFiles.FirstOrDefault(x => x.Id == Id_LogServerLogFile);
    byte[] data = logServerLogFile.LogServerLogFilesData.TFFileData;
    long sz = logServerLogFile.TFFileSize;
    Response.ClearContent();
    Response.ContentType = logServerLogFile.TFFileMimeType;
    Response.AddHeader("Content-Disposition", string.Format("attachment; filename = " + logServerLogFile.TFFileName));
    Response.AddHeader("Content-Length", sz.ToString("F0"));
    Response.Expires = 30;
    Response.Buffer = true;
    Response.BinaryWrite(data);
    Response.Flush();
    Response.End();
}

EDIT : If you are using EF5, you can set `connection timeout` in the config:

<connectionStrings>

    <add name="AdventureWorksEntities"       connectionString="metadata=.\AdventureWorks.csdl|.\AdventureWorks.ssdl|.\AdventureWorks.msl;
provider=System.Data.SqlClient;provider connection string='Data Source=localhost;
Initial Catalog=AdventureWorks;Integrated Security=True;Connection Timeout=180;
multipleactiveresultsets=true'" providerName="System.Data.EntityClient" />

</connectionStrings>

Or in the context:

public class SFTDBEntities : DbContext
{
    public SFTDBEntities ()
        : base(ContextHelper.CreateConnection("Connection string"), true)
    {
        ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 180;
    }
}

SOURCE: Set database timeout in Entity Framework.

Problem

I am trying to download file from database using following code : ``` using(SFTDBEntities db = new SFTDBEntities()) { Guid Id_LogServerLogFile = Guid.Parse(lblId.Text.Trim()); LogServerLogFile logServerLogFile = new LogServerLogFile(); logServerLogFile = db.LogServerLogFiles.FirstOrDefault(x = > x.Id == Id_LogServerLogFile); byte[] data = logServerLogFile.LogServerLogFilesData.TFFileData; long sz = logServerLogFile.TFFileSize; Response.ClearContent(); Response.ContentType = logServerLogFile.TFFileMimeType; Response.AddHeader("Content-Disposition", string.Format("attachment; filename = " + logServerLogFile.TFFileName)); Response.AddHeader("Content-Length", sz.ToString("F0")); Response.Expires = 30; Response.Buffer = true; Response.BinaryWrite(data); Response.Flush(); Response.End(); } ``` for files with small size It works fine , but when I try to download a large file (ex: 27 MB) at the following line : ``` byte[] data = logServerLogFile.LogServerLogFilesData.TFFileData; ``` I get the following error : ``` Invalid attempt to call IsDBNull when reader is closed. ``` any helps would be appreciated .

Original source

Related problems