1

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?

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

2 Comments

I recommend the use of ConfigureAwait( false )
@SirRufo Right. OP mentioned XAML markup, so I'm not entirely sure OP's doing it off the UI thread.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.