I am performing a query in which I project the query into a business object that uses Lists. The problem is that Linq to entities is complaining that “Only parameterless constructors and initializers are supported in LINQ to Entities.”
I’ve been pulling my hair out over this one. My query looks something like this:
var q = from d in db.Items select new BusinessObject
{
MyList = new List<MyObject>(d.Select(x => new MyObject {// set fields})
}
I can’t use the initializer as that only seems to accept a single item, not the collection of them. I can’t do a .ToList() because EF then complains that it doesn’t know what a list of MyObject is (apparently, it’s trying to convert it to SQL).
I can’t create the List outside of the query, because i need a new list for each row in the parent table.
Any suggestions here?
The query looks strange to me – what is db? is it supposed to be your context or an IQueryable property for your context?
Assuming its your context, you could try eager loading the items property (what is this a collection of?) when you query for the BusinessObject collection, then convert to a List and then project the items property into a List on the in-memory collection: