Keeping it simple: I'd like to populate a custom type with a list in it.
List<ParentModel> parentModelList =
(from c in _context.children
join p in _context.parents on c.ParentId equals p.ParentId
orderby c.BirthDate
where p.GenderId = gender.GenderId // Could be a male parent or female or whatever
group c by p into childGroup
select new ParentModel()
{
ParentId = p.ParentId,
ChildList = childGroup.Select(x => new ChildModel()
{
ChildId = childGroup.Key.ChildId,
ChildName = childGroup.FirstOrDefault().ChildName,
}).ToList()
}).ToList();
You can probably guess where my issue is. I can't call ToList() in the middle of a linq to Entities query otherwise I'd get this runtime Exception:
A type that implements IEnumerable cannot be initialized in a LINQ to Entities query
I'm connecting to a MySql database using EF6 where context is my dbContext. Below are the stores:
public class ParentModel
{
public int ParentId { get; set; }
// other properties...
List<ChildModel> ChildList { get; set; }
}
public class ChildModel
{
public int ChildId { get; set; }
public string ChildName { get; set; }
}
So, how would I write this query in order to retrieve information as expected? I'd prefer not to drop out of the operation and run a foreach over the results. Any enlightenment would be greatly appreciated.
.ToList()when you sayI can't call ToList() in the middle of a linq to SQL query?.ToList()works fine in Entity Framework. This could be due to your MySQL database connector (I've heard bad things about the official MySQL connector for Entity Framework). But the error you're reporting usually happens when you try to initialize a property as anew List<...>(). Is it possible that in "keeping it simple" you omitted a line of code which does that?.ToList()you are creating an in memory query tree. At the moment you execute the.ToList()the query is executed and the result resolved.