尝试使用Entity Framework从数据库下载大文件时出错

时间:2014-01-15 08:15:25

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

我正在尝试使用以下代码从数据库下载文件:

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();
}

对于小尺寸的文件它工作正常,但当我尝试下载一个大文件(例如:27 MB) 在以下行:

byte[] data = logServerLogFile.LogServerLogFilesData.TFFileData;

我收到以下错误:

Invalid attempt to call IsDBNull when reader is closed.

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:4)

您需要增加命令超时:

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();
}

编辑: 如果您使用的是EF5,则可以在配置中设置connection timeout

<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>

或者在上下文中:

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

消息来源:Set database timeout in Entity Framework