使用EF检索数据时,从ImagePath创建BitmapImage的新实例

时间:2017-12-18 11:02:37

标签: c# sql entity-framework linq bitmapimage

当我从SQL数据库检索数据时,尝试从imagepath创建新的BitmapImage时出现此错误:

  

LINQ中仅支持无参数构造函数和初始值设定项   实体。

我在using块中创建一个DbContext,它选择Equipment记录创建的EquipmentLookup类实例来保存部分数据。

using (var ctx = _contextCreator())
            {
                return await ctx.Equipments.AsNoTracking().Select(f => new EquipmentLookup
                {
                    EquipmentId = f.EquipmentId,
                    SerialNumber = f.EquipmentSerialnumber,
                    TypeName = f.EquipmentType.EquipmentTypeName,
                    Image = new BitmapImage(new Uri(f.EquipmentImagePath))

                }).ToListAsync();
            }

对于图像我不想要图像路径,但是创建一个适合XAML标记的新BitmapImage。当我在对象实例化中调用这样的构造函数时,我得到上述错误。在这种情况下不可能调用构造函数吗?

EquipmentLookup类:

public class EquipmentLookup
    {
        public EquipmentLookup()
        {

        }
        public int EquipmentId { get; set; }
        public string SerialNumber { get; set; }
        public string TypeName { get; set; }
        public BitmapImage Image { get; set; }
    }

如何在上下文中从imagepath创建BitmapImage?我是否需要将实例化移动到其他地方?

1 个答案:

答案 0 :(得分:2)

“LINQ to Entities”中不支持“[XYZ]”的常见解决方案是通过调用AsEnumerable()ToList()将操作移至LINQ to Objects:

// This is processed in LINQ to Entities
var equipments = await ctx.Equipments.AsNoTracking().ToListAsync();
// After awaiting ToListAsync() we are in LINQ to Objects territory:
return equipments.Select(f => new EquipmentLookup {
       EquipmentId = f.EquipmentId,
       SerialNumber = f.EquipmentSerialnumber,
       TypeName = f.EquipmentType.EquipmentTypeName,
       Image = new BitmapImage(new Uri(f.EquipmentImagePath))
   }).ToList();