0
Answer

display image from the SQL database using EF and LINQ

Ask a question
Gerdi

Gerdi

12y
2.6k
1
I just want to display the image from the database. nothing major.

I am using WPF and the entity framework with linq to call to the database and it seems not one on the entire interweb have every posted on this. .. ever

this is my code to upload the image

 try
            {

                //proceed only when the image has a valid path
                if (txtbxImage.Text != "")
                {

                    FileStream fs;
                    fs = new FileStream(@txtbxImage.Text, FileMode.Open, FileAccess.Read);

                    //a byte array to read the image
                    byte[] picbyte = new byte[fs.Length];
                    fs.Read(picbyte, 0, System.Convert.ToInt32(fs.Length));
                    fs.Close();

                    addEmployee.Image = picbyte;
                }

            }

            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);

            }


pretty simple. So I get a <binary> in the database but now i want to display the damn thing.

from a few hours of searching i got this far

Byte[] data = new Byte[0];
data = (query.Image);
MemoryStream mem = new MemoryStream(data);

// create variable to add to be able to use in entity query
var test = System.Drawing.Image.FromStream(mem);

the LINQ to get the require fields is

var query = (from a in context.Employees
                     where txtbxEmpNumber.Text == a.EmployeeNumber
                     select a).FirstOrDefault();

so now if i write

txtbxAddFirstName.Text = query.FirstName;

the selected first name goes into the database . But when i try

empImg.Source // OR emp.Image  = test;

That does not work. The error seems to say that test has not been coverted yet from a byte to whatever it needs to be .. geez i actually have no freaking clue what i am doing here. I just cant find any resources that come close to trying to clarify this. They either using webforms or asp or the tutorials are all from the early 2000 .....or they using sql connects which dont seem to be relevant with EF and LINQ ... why would anyone use standard sql inside c# instead of LINQ

Anyways ... any help would be awesome.

Cheers 
Gerdi