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

问题描述 投票:1回答:1

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

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

我在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?我需要将实例移动到其他地方吗?

c# sql entity-framework linq bitmapimage
1个回答
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();
© www.soinside.com 2019 - 2024. All rights reserved.