使用 EF 检索数据时从 ImagePath 创建 BitmapImage 的新实例
Creating new instance of BitmapImage from ImagePath when retrieving data using EF
当我从 SQL 数据库检索数据时,尝试从图像路径创建新的 BitmapImage 时出现此错误:
Only parameterless constructors and initializers are supported in LINQ
to Entities.
我正在使用块中创建一个 DbContext,它选择设备记录并创建 EquipmentLookup classes 实例以保存部分数据。
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。当我在对象实例化中这样调用构造函数时,出现上述错误。在这种情况下不能调用构造函数吗?
设备查找class:
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; }
}
如何从上下文中的图像路径创建 BitmapImage?我需要将实例化移到别处吗?
“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();
当我从 SQL 数据库检索数据时,尝试从图像路径创建新的 BitmapImage 时出现此错误:
Only parameterless constructors and initializers are supported in LINQ to Entities.
我正在使用块中创建一个 DbContext,它选择设备记录并创建 EquipmentLookup classes 实例以保存部分数据。
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。当我在对象实例化中这样调用构造函数时,出现上述错误。在这种情况下不能调用构造函数吗?
设备查找class:
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; }
}
如何从上下文中的图像路径创建 BitmapImage?我需要将实例化移到别处吗?
“LINQ to Entities 不支持 [XYZ]”问题的常见解决方案是通过调用 AsEnumerable()
或 ToList()
:
// 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();