Longshadow
Longshadow

Reputation: 109

Convert byte[] array TO sqldbtype.Varbinary using Dapper

I've found a code snipped on the Internet that inserts a document as a byte array in the database. It is as follows:

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

Now, I have to apply that to Dapper/Entity framework, but so far, without success. What I got so far is as follows:

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

The key line here is:

         sqlWrite.Parameters.Add("@File", SqlDbType.VarBinary, file.Length).Value = file;

As is the one that sets the data type to VarBinary. I really need some help here...

The file array is anexoBytes.

Upvotes: 4

Views: 14762

Answers (1)

G Davison
G Davison

Reputation: 1099

Dapper can handle the assignments through an anonymous type that will take the place of the parameter values, so in your example, you would just change your SQL to define some parameterised SQL, then pass in the new object that contains the values for those parameters. This will automatically map the values up to their parameters and avoid the need to manually define them or perform string replacement on your 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 });

Upvotes: 5

Related Questions