c# - 将 SQL Server 文件流与 LINQ 结合使用

标签 c# sql-server linq sqlfilestream

使用 LINQ 访问数据库中的 BLOB 文件是这样的:

var query = from file in database 
where file.FileID = fileId 
select file;

当我在此表上激活 Filestream 时,LINQ 通过 T-SQL 查询数据库。对于较大的文件,这是一种不好的做法。

根据本网站:http://www.codeproject.com/Articles/128657/How-Do-I-Use-SQL-File-Stream它应该使用 SqlCommand 完成,查询路径,然后使用 SqlFileStream 直接访问文件。

Select FileData.PathName() As Path,
GET_FILESTREAM_TRANSACTION_CONTEXT() As TransactionContext
From PictureTable Where PkId = (Select Max(PkId) From PictureTable)

现在是否可以更流畅(更像“LINQ-er”)方式访问文件?

最佳答案

最终这将不是 LINQ 查询,因为您必须将 LINQ 查询转换为经典 SQL 查询(通过使用 DataContext.GetCommand )并从 SqlCommand 调用 BeginExecuteReader。

public class TerrasoftFiles : ITerrasoftFiles
{
    public TerrasoftFiles()
    {
        this.sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["TTDataReader"].ConnectionString);
        this.sqlCommand = new SqlCommand(@"SELECT FileData FROM tbl_Files WHERE ID = @ID", sqlConnection);
    }

    private SqlConnection sqlConnection;
    private SqlCommand sqlCommand;

    public IAsyncResult BeginGetFiles(Guid ID, AsyncCallback asyncCallBack, object asyncState)
    {
        sqlCommand.Parameters.Add(new SqlParameter("@ID", ID));

        sqlConnection.Open();

        return sqlCommand.BeginExecuteReader(asyncCallBack, asyncState);
    }

    public Stream EndGetFiles(IAsyncResult asyncResult)
    {
        using(sqlConnection as IDisposable)
           using (sqlCommand as IDisposable)
                using (var Reader = sqlCommand.EndExecuteReader(asyncResult))
                {
                    return (Reader.Read()) ? Reader.GetSqlBytes(0).Stream : Stream.Null;
                }
    }
}

关于c# - 将 SQL Server 文件流与 LINQ 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19558334/

相关文章:

SQL Server : inserting multi-table output from stored procedure into separate tables

php - 如何在 Dreamweaver 中设置 PHP 测试服务器?

sql-server - 如何注释掉报告服务函数中的一行?

c# - 搜索属性名称包含连字符/破折号的 XElement

C#:Monitor.Pulse() 不起作用

c# - 如何将字符串插入文字字符串

c# - 如何使用 Regex.Replace 从字符串中删除数字?

c# - 存储对值类型的引用?

c# - 通过匿名传递列名对通用列表的一列求和

c# - 复杂的 Linq 查询