Error doing UPDATE when setting varbinary variable as`null`

Asked

Viewed 147 times

5

Follows code:

var file = Request.Files;
var list = new List<byte[]>();

for (int i = 0; i < 4; i++)
{
    if (file.Count > i)
    {
        list.Add(ConvertTo.Bytes(file[i]));
        continue;
    }
    list.Add(null);
}

int count = ctx.Database.ExecuteSqlCommand(
    $"UPDATE dbo.Table " +
    $"SET Imagem1 = @imagem1, Imagem2 = @imagem2, Imagem3 = @imagem3, Imagem4 = @imagem4 " +
    $"WHERE id = {Id}",
    new SqlParameter("imagem1", list[0] ?? null),
    new SqlParameter("imagem2", list[1] ?? null),
    new SqlParameter("imagem3", list[2] ?? null),
    new SqlParameter("imagem4", list[3] ?? null));

Error:

The parameterized query '(@imagem1 varbinary(max) ,@imagem2 nvarchar(4000),@imagem3 nvarc' expects parameter '@imagem2', other than was provided.

This error happens when user chooses only one image.

Some solution ?

  • debugging the contents of the list[1] ?

  • if Voce chooses 2 images gives error in 3?

  • @imagem1 varbinary(max) ,@imagem2 nvarchar(4000),@imagem3 nvarc ?????? all parameters are varbinary? not understood now.. the first seems to be different from the others..

  • yes.. but it’s strange that he says that the types are different... in his database as it is ?

  • guy tries to put this: in his Parameters new Sqlparameter("imagem1", System.Data.Sqldbtype.Varbinary). Value = list[0];

  • 1

    @Matheusmiranda You need to use SqlBinary.Null

  • That’s right @LINQ, the problem has been solved, thank you.

Show 3 more comments

1 answer

8


Matheus you need to change the null for Sqlbinary.Null, many people had this problem with null and varbinary values in the bank!

int count = ctx.Database.ExecuteSqlCommand(
    $"UPDATE dbo.Table " +
    $"SET Imagem1 = @imagem1, Imagem2 = @imagem2, Imagem3 = @imagem3, Imagem4 = @imagem4 " +
    $"WHERE id = {Id}",
    new SqlParameter("imagem1", list[0] ?? SqlBinary.Null),
    new SqlParameter("imagem2", list[1] ?? SqlBinary.Null),
    new SqlParameter("imagem3", list[2] ?? SqlBinary.Null),
    new SqlParameter("imagem4", list[3] ?? SqlBinary.Null));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.