storing image inside db using winforms

c# dapper sql-server winforms

Question

I want to save Image inside SqlServer using c# winforms and dapper micro orm.

Photo field inside db is of type VARBINARY(MAX)

Inside Book entity I have Photo property of type byte[].

public Book 
{
   ... 
   public byte[] Photo { get; set; }
}

Inside winforms Window I have

  OpenFileDialog open = new OpenFileDialog() { Filter = "Image Files(*.jpeg;*.bmp;*.png;*.jpg)|*.jpeg;*.bmp;*.png;*.jpg" };
   if (open.ShowDialog() == DialogResult.OK)
   {
       txtPhoto.Text = open.FileName;
   }

   string image = txtPhoto.Text;
   Bitmap bmp = new Bitmap(image);
   FileStream fs = new FileStream(image, FileMode.Open, FileAccess.Read);
   byte[] bimage = new byte[fs.Length];
   fs.Read(bimage, 0, Convert.ToInt32(fs.Length));
   fs.Close();

   byte[] Photo = bimage;

// inside my repository I have error on saving object at line Photo = @Photo

var sql = "UPDATE Book " +
          "SET Title = @Title, " +
          "    Language = @Language, " +
          ....
          "    Photo = @Photo" +
          "WHERE Id = @Id";

          this.db.Execute(sql, book); // error occures
          return book;

Error is

A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

Additional information: Incorrect syntax near 'Photo'.

Am I missing something?

Thanks

Accepted Answer

You are missing white space before WHERE keyword:

      "    Photo = @Photo" + // no space at the end here
      "WHERE Id = @Id";      // and no space before WHERE here

Also I suggest you to use multiline string (i.e. verbatim string literal) for sql query text (that makes query more readable):

var sql = @"UPDATE Book 
            SET Title = @Title, 
                Language = @Language, 
                Photo = @Photo
            WHERE Id = @Id";

And one more thing - it's better to wrap Stream usage into using block (in order to release file handle in case of exception):

byte[] photo;
using(var stream = File.OpenRead(txtPhoto.Text)
{
    photo = new byte[stream.Length];
    stream.Read(photo, 0, photo.Length);
}

// db query with dapper is OK


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why