Good day,
My code generates a run-time error and I’m not sure how to fix this. Any help would be appreciated.
Our code is calling the second Convert method below by passing a list of “offers”. The offer is an object from an EDMX model. The first Convert method takes the object and converts it to a DTO class which it then returns back.
When running the program, I experience the following error:
LINQ to Entities does not recognize the method ‘…Domain.Holdings.OfferDto Convert(…Repository.Offer, System.Nullable`1[System.Int32])’ method, and this method cannot be translated into a store expression.
The code looks as follows:
public class OfferDtoMapping
{
public static OfferDto Convert(Offer offer, int? participantId)
{
if (offer == null)
throw new ArgumentException("The Offer object supplied for conversion cannot be null");
var unitCost = offer.UnitCost;
if (offer.Trust.Company.AllowInterDiv && participantId.HasValue)
{
Assign another value to unitCost...
}
var output = new OfferDto
{
Assign the offer properties to the OfferDto properties...
};
return output;
}
public static IList<OfferDto> Convert(IQueryable<Offer> offerList)
{
return offerList == null ? new List<OfferDto>() : offerList.Select(ol => Convert(ol, null)).ToList();
}
}
The error occurs on this line:
return offerList == null ? new List<OfferDto>() : offerList.Select(ol => Convert(ol, null)).ToList();
I suspect the error has to do with the fact that I am projecting the offerList over a method taking in 2 input parameters. We tried passing 0 instead of NULL (because we initially thought that was the problem) but still got a similar error message.
In order to maintain consistency throughout our solution we want to keep using the Select method instead of replacing this with a foreach statement.
Is there a way of using the Select method in our current situation?
Thank you in advance.
The error occurs because there is no transaltion for the Convert method in Linq to entities. You need to force evaluation of the data first by calling ToList() on the Iqueryable data. The convert can then be executed outside of Linq to Entites in memory.