简体   繁体   English

无法使用Dapper.NET将文件流插入SQL文件表

[英]Unable to insert file stream into SQL filetable using Dapper.NET

I am using Dapper.NET as ORM layer in my project. 我在项目中使用Dapper.NET作为ORM层。 I am trying to write WebApis for file upload and download. 我正在尝试为文件上传和下载编写WebApis。 However I am not able to get it working. 但是我无法使其工作。 I have already searched enough to look for help but I couldn't find any. 我已经进行了足够的搜索以寻求帮助,但找不到任何帮助。

If I was simply using ADO.NET, I could have used SqlParameter of type VarBinary for the file stream. 如果仅使用ADO.NET,则可以将VarBinary类型的SqlParameter用于文件流。 But Dapper.NET query parameters is just dynamic object. 但是Dapper.NET查询参数只是动态对象。 So following code fails to insert the record into filetable. 因此,以下代码无法将记录插入到文件表中。

var fileStream = await Request.Content.ReadAsStreamAsync();

var streamId = Guid.NewGuid();
var fileName = streamId.ToString();

var sql = @"Insert into Attachments(stream_id, file_stream, name)
            Values(@streamId, @fileStream, @fileName)";

using (var db = new SqlConnection(AppConfig.ConnectionString))
{
    await db.ExecuteAsync(sql, new { streamId, fileStream, fileName);
}

fileStream.Close();

Exception thrown: 'System.NotSupportedException' in mscorlib.dll 引发异常:mscorlib.dll中的“ System.NotSupportedException”

Additional information: The member fileStream of type System.IO.Stream cannot be used as a parameter value 附加信息:类型System.IO.Stream的成员fileStream不能用作参数值

Has anyone done this or be aware of any dapper extension plugin I could use? 有没有人这样做或知道我可以使用的任何dapper扩展插件?

You need to use the DynamicParameters class and specify the parameter's data type. 您需要使用DynamicParameters类并指定参数的数据类型。 For the example I created a table TEST with a column called Stream VARBINARY(MAX) 对于该示例,我创建了一个表TEST以及一个名为Stream VARBINARY(MAX)的列

using (var connection = new SqlConnection(Properties.Settings.Default.connectionString))
{
    connection.Open();
    using (var fs = File.Open(Properties.Settings.Default.filePath, FileMode.Open))
    {
        var sql = "INSERT INTO TEST (Stream) VALUES (@fs)";

        var dParams = new DynamicParameters();
        dParams.Add("@fs", fs, DbType.Binary);

        connection.Execute(sql, dParams);
    }
}

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

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