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:
UPDATE:
After your comments below, I'd suggest you to also check for the case when you image exists in database, but the photo array is null.
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!");
//update: check for the case when a FarmerImage exists in database but the photo array is null
if (image.photo == 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;
}
}
Remember that you could call the method and handle the exceptions - I'd do it this way - or you could return null instead of throwing an exception and the handle the case when the returned image is null.
First case: expecting an exception
public void CallerHanderOrMethod()
{
try{
var img = farmerManager.getPhoto(farmerId);
}
catch(Exception ex) //consider throwing a more specific exception.
{
//load the default silhouette image into the picture box.
}
}
Second case: expecting a null image.
public void CallerHanderOrMethod()
{
var img = farmerManager.getPhoto(farmerId);
if (img == null)
{
//load the default silhouette image into the picture box.
}
}
This should do the work.
Hope this helps!