ExecuteSqlCommand - Update byte - Error

1

Follow the code below:

var bytes = ConvertTo.Bytes(file);

int num = ctx.Database.ExecuteSqlCommand(
    $"UPDATE dbo.Table" +
    $"SET Video = '{bytes}' " +
    $"WHERE id = {Id} ");

Follow the code to convert:

public static byte[] Bytes(HttpPostedFileBase file)
{
    var length = file.InputStream.Length;
    byte[] fileData = null;
    using (var binaryReader = new BinaryReader(file.InputStream))
    {
        fileData = binaryReader.ReadBytes(file.ContentLength);
    }
    return fileData;
}

I get error:

  

The implicit conversion of the varchar data type into varbinary (max) is not   allowed. Use the CONVERT function to execute this query.

Any solution?

    
asked by anonymous 09.11.2017 / 15:26

1 answer

2

You should use queries parameterized to do this work.

Anyway, you can do it this way:

var valor = "0x" + BitConverter.ToString(arraytoinsert).Replace("-", "");

int num = ctx.Database.ExecuteSqlCommand(
          $"UPDATE dbo.Table" +
          $"SET Video = {valor} " +
          $"WHERE id = {Id} ");

Using a parameterized query, it would look like this:

using(SqlCommand cmd = new SqlCommand("UPDATE dbo.Table SET Video = (@pVideo)", conn))
{
    cmd.Parameters.Add("@pVideo", SqlDbType.VarBinary, 8000).Value = bytes;
    cmd.ExecuteNonQuery();
}
    
09.11.2017 / 15:40