我在 Internet 上找到了一段代码,它将文档作为字节数组插入到数据库中。具体如下:
public void databaseFilePut(string varFilePath)
{
byte[] file;
using (var stream = new FileStream(varFilePath, FileMode.Open, FileAccess.Read))
{
using (var reader = new BinaryReader(stream))
{
file = reader.ReadBytes((int)stream.Length);
}
}
//using (var varConnection = Locale.sqlConnectOneTime(Locale.slqDataConnectionDetails))
using (SqlConnection connection = new SqlConnection(connectionString))
using (var sqlWrite = new SqlCommand("INSERT INTO EXCEL_EM_BYTES (DOCUMENTO_BYTES) Values(@File)", connection))
{
sqlWrite.Parameters.Add("@File", SqlDbType.VarBinary, file.Length).Value = file;
connection.Open();
sqlWrite.ExecuteNonQuery();
connection.Close();
}
}
现在,我必须将其应用于 Dapper/Entity 框架,但到目前为止,还没有成功。目前我得到的结果如下:
public void InsereRegistroEmail(string a, string b, string c, byte[] anexoBytes)
{
//var cn = _context.Database.Connection;
//cn.Execute(string.Format(QueriesSAC.InsereRegistroEmailBanco, motivoEmail, nomeGestor, corpoEmail, anexoBytes));
var cn = _context.Database.Connection;
//var A = new SqlParameter("@A", SqlDbType.VarBinary, anexoBytes.Length);
//A.Value = anexoBytes;
var sql =(string.Format("INSERT INTO [LOG_EMAIL] ([GSTOR_DSTNA] ,[ASSNT],[DATA_ENVIO],[CORPO_EMAIL],[ANEXO]) VALUES('{0}','{1}', GETDATE(),'{2}', @A)", a, b, c));
var A = new DynamicParameters();
A.Add("@A", anexoBytes, dbType: DbType.Binary, direction: ParameterDirection.Input);
A.Get<DbType>("@A");
cn.Execute(sql);
}
这里的重点是:
sqlWrite.Parameters.Add("@File", SqlDbType.VarBinary, file.Length).Value = file;
与将数据类型设置为 VarBinary 的一样。我真的需要一些帮助...
文件数组是anexoBytes。
最佳答案
Dapper 可以通过代替参数值的匿名类型处理分配,因此在您的示例中,您只需更改 SQL 以定义一些参数化 SQL,然后传入包含以下值的新对象那些参数。这将自动将值映射到它们的参数,避免手动定义它们或对 SQL 执行字符串替换的需要。
_connection.Execute("INSERT INTO [LOG_EMAIL] ([GSTOR_DSTNA] ,[ASSNT],[DATA_ENVIO],[CORPO_EMAIL],[ANEXO]) VALUES(@DstNa, @Assnt, GETDATE(), @CorpEmail, @Anexo",
new { DstNa = a, Assnt = b, CorpEmail = c, Anexo = anexoBytes });
关于c# - 使用 Dapper 将 byte[] 数组转换为 sqldbtype.Varbinary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41699519/