使用c#实体框架从SQL数据库获取图像类型

本文关键字:数据库 获取 图像 类型 SQL 实体 框架 使用 | 更新日期: 2023-09-27 18:09:21

我想从我的数据库表中获得Image列的值。

我以前使用过这段代码,但现在我想调用一个函数从另一个表中查询它。

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

下面的代码抛出一个错误:

不能隐式转换类型"System.Linq"。到System.Drawing.Image。存在显式转换

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;
    }
}

使用c#实体框架从SQL数据库获取图像类型

问题是您的linq查询返回IQueryable<Image>而不是单个Image对象,因此您不能从仅返回图像的方法返回它。你只需要得到一个值。

你可以这样写:

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();
}

但是你会得到一个运行时异常:

附加信息:LINQ to Entities不识别该方法'System.Drawing.Image FromStream(System.IO.Stream)'方法,以及这个方法不能转换为存储表达式。

我首先从数据库中获取FarmerImage元数据,处理可能的异常-例如。image不存在-然后返回Image对象:

更新:在你下面的评论之后,我建议你也检查一下当你的图像存在于数据库中,但photo数组为空的情况。

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;
    }
}

请记住,您可以调用该方法并处理异常-我将这样做-或者您可以返回null而不是抛出异常并处理返回的图像为null的情况。

第一种情况:期望出现异常

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. 
    }
}

第二种情况:期望一个空图像。

public void CallerHanderOrMethod()
{
    var img = farmerManager.getPhoto(farmerId);
    if (img == null) 
    {
        //load the default silhouette image into the picture box. 
    }
}

这个应该能起作用。

希望这对你有帮助!