我发现在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。
答案 0 :(得分:4)
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 });