I am trying to write a LINQ query that fetches a list of Course
entities and their mapped Skill
children. The are related with a join table with corresponding CourseId
and SkillId
. I wish to sort the Skill
children with the Weight
property and then with the SkillId
property. I am using dot net core 2.0.
After looking at similar questions on how to sort/order a list of children to an entity here:
I have come up with this:
// Create query to get all courses with their skills
var coursesWithUnorderedSkills= db.Courses
.Include(i => i.Skills)
.ThenInclude(i => i.Skill);
// Order the skills for each course
await coursesWithUnorderedSkills.ForEachAsync(x => x.Skills = x.Skills
.OrderBy(o => o.Weight)
.ThenBy(o => o.SkillId)
.ToList());
// Get a list of courses from the query
var coursesWithOrderedSkills = await q.ToListAsync();
How can this be simplified into a single query and will this query have any unexpected performance issues since I am calling ToList
in the ForEachAsync
call?
Models
public class Course
{
[Key]
public int Id { get; set; }
public List<CourseSkill> Skills { get; set; }
}
public class CourseSkill
{
public Course Course { get; set; }
public int CourseId { get; set; }
public Skill Skill { get; set; }
public int SkillId { get; set; }
public int Weight { get; set; } = 0;
}
public class Skill
{
[Key]
public int Id { get; set; }
}