ivias ivias - 2 months ago 10
C# Question

Get Image Type from SQL database using C# Entity Framework

I want to get the value of an

Image
column from my database table.

I used this code before, but now I want to call a function to query it from another table.

MemoryStream ms = new MemoryStream(obj.photo, 0, obj.photo.Length);
ms.Position = 0; // this is important
pbFarmer.Image = Image.FromStream(ms, true);


This code throws an error:


Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Drawing.Image'. An explicit conversion exists


public Image getphoto(int id)
{
using (simisdbEntities db = new simisdbEntities())
{
// return db.FarmerImages.Where(u => u.id == id).Select(u => u.photo);
// return db.FarmerImages.SqlQuery("SELECT photo FROM dbo.FarmersImages where id =" + id);

// return db.FarmerImages.First(a => a.id == id);

var img = from p in db.FarmerImages
where p.id == id
select Image.FromStream(new MemoryStream(p.photo.ToArray()));
return img;
}
}

Answer

The problem is that your linq query is returning IQueryable<Image> instead of a single Image object so you can not return it from your method that returns only an Image. You need to somehow get only one value.

You could go with something like this:

using (simisdbEntities db = new simisdbEntities())
{
    IQueryable<Image> img = from p in db.FarmerImages 
                            where p.id == id 
                            select Image.FromStream(new MemoryStream(p.photo.ToArray()));
    return img.FirstOrDefault();
}

But then you'll get a run time exception:

Additional information: LINQ to Entities does not recognize the method 'System.Drawing.Image FromStream(System.IO.Stream)' method, and this method cannot be translated into a store expression.

I'd first get the FarmerImage metadata from the database, handle the possible exceptions - eg. image does not exist - and then return the Image object:

public Image getphoto(int id)
{
    using (var db = new simisdbEntities())
    {
        var imgMetadata = db
                .FarmerImages
                .FirstOrDefault(p => p.id == id);

        //handle the case when image does not exist.
        if (imgMetadata == null)
            throw new Exception("Image not found!");

        //read the image bytes into an Image object.
        var img = Image.FromStream(new MemoryStream(imgMetadata.photo.ToArray()));

        return img;
    }
}

This should do the work.

Hope this helps!

Comments