0
public byte[] ReturndbImage()
    {
        Image_table table = new Image_table();
        var row = from s in db.Image_tables
                  where s.Id == 1
                  select s.imag;
        byte[] b = null ;
        int cou = row.Count();
        b = (byte[])(row).Single().ToArray(); 
        return b;
    }

hi i am using Microsoft visual studio 2013 and I am trying to get image stored in database using linq .i am unable to get image. my image is stored in db as varbinary<> .I am unable to convert back to binary[].i have records in database It still give null value.

user3402966
  • 17
  • 1
  • 8
  • Which ORM are you using? If it's Entity Framework then normally, IIRC, the `imag` property should already be of type `Byte[]`. Also, the fact that you have records doesn't mean that your records doesn't hold null values for `imag`. – Crono May 14 '14 at 17:45
  • What is being returned in `row`? Your code doesn't have any obvious errors that jump out. – Ben Black May 14 '14 at 17:46
  • [This might help you](http://stackoverflow.com/questions/12482687/datatable-with-a-byte-field-as-parameter-to-a-stored-procedure) – kei May 14 '14 at 17:48
  • i am trying to get varbinary<> column values from database.in row i am trying to store that varbinary data . – user3402966 May 14 '14 at 17:54
  • @user3402966 Not answering comments is the best way to get your question closed as "unclear what your asking". – Gert Arnold May 14 '14 at 18:42

1 Answers1

4

You should probably just return the image from your Data Base as an Image rather than a byte[].

if s.imag is of type VARBINARY then LINQ will contain it as System.Data.Linq.Binary, so you can just create the image directly from that binary, using a MemoryStream.

Try the following:

public Image ReturnDbImage()
{
    var dbBinary = (from s in db.Image_tables
               where s.Id ==1
               select s.imag).FirstOrDefault();
    if (dbBinary == null)
    {
        //Handle the issue
    }
    else
    {
        using (var ms = new MemoryStream(dbBinary.ToArray()))
        {
            Image img = Image.FromStream(ms);
            return img;
        }
    }
}

I have removed the unnecessary variables cou and table from the method as you are not using them anywhere.

Evan L
  • 3,805
  • 1
  • 22
  • 31