I have a simple Parent/Child table and I want to populate with one SQL statement using Entity Framework. Something like this:
public class Parent
{
public long ParentId { get; set; }
public virtual List<Child> Children { get; set; }
}
public class Child
{
public long ChildId { get; set; }
public long ParentId { get; set; }
public DateTime DateCreated { get; set; }
}
public Parent GetParent (long parentId)
{
IQueryable<Parent> query =
(from a in db.Parents.Include("Children")
where a.ParentId == parentId
select a);
return query.FirstOrDefault();
}
This seems to work in fetching the Parent and all Children in one SQL Statement. What I want to do now is order the children list by the DateCreated field, but I can’t figure out how to do that. I’ve seen posts about using ThenBy() but don’t see how to inject in the above Linq. Is there a better way I should be formulating the Linq?
-shnar
Unfortunately this is not supported. You cannot order included records by Linq-to-entities. Only parent records can be ordered. But you can still do something like: