Leth
Leth

Reputation: 1059

Creating new instance of BitmapImage from ImagePath when retrieving data using EF

I am getting this error when trying to create a new BitmapImage from an imagepath when I retrieve data from an SQL database:

Only parameterless constructors and initializers are supported in LINQ to Entities.

I am creating a DbContext in an using block, that selects Equipment records an creates instances of EquipmentLookup classes to save part of the data.

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

For the image I do not want the image path, but create a new BitmapImage that is suitable for XAML markup. When I call a constructor like so in the object instantiation i get the above error. Is it not possible to call constructors in this context?

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

How can I create a BitmapImage from the imagepath in my context? Do I need to move the instantiation elsewhere?

Upvotes: 1

Views: 73

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

A common solution to "[XYZ] is not supported in LINQ to Entities" problem is moving the operation to LINQ to Objects by invoking AsEnumerable() or 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();

Upvotes: 2

Related Questions