Include Filters for Entity Framework Core

asp.net-core entity-framework-core linq

Question

I've been trying to find out information about filtering my calls to the database to reorder the data from the database and have found out their is no way yet to filter the .Inclunde or .ThenInclude.

Below is what I have tried, is there a way of sorting a collection?

var workout = await context.Workouts
                           //.Include(w => w.Segments.OrderByDescending(x => x.Id))
                           .Include(w => w.Segments)
                           .ThenInclude(s => s.Sets)     //this gets the sets for the segment
                           .Include(w => w.Segments)
                           .ThenInclude(s => s.Exercise)     //try intellisense didn't show exercise
                           .Include(w => w.BodyParts)       //to delete from bodyparts column need to fix
                           .SingleOrDefaultAsync(w => w.Id == id);


   .Include(w => w.Segments.OrderByDescending(x => x.Name))  //doesn't work

   .ThenInclude(s => s.Sets.OrderByDescending(x => x.Name))  //doesn't work 

Below code can't convert order IEnumerable to my domain

var workoutSegments = workout.Segments.OrderByDescending(x => x.Name);

foreach( var segment in workout.Segments)
{
    segment.Sets.OrderByDescending(x => x.Name).ToList();
}    

return workoutSegments;

public class Workout
{
    public int Id { get; set; }
    public string UserId { get; set; }
    public string Name { get; set; }

    public ICollection<Segment> Segments { get; set; }

    public Workout()
    {
        Segments = new Collection<Segment>();
    } 
}
1
0
1/19/2020 7:00:32 AM

Popular Answer

There is 3rd party library to do orderby in include. I cannot remember what name. But I have another way.

var workout = await context.Workouts
     .Include(w => w.Segments)
        .ThenInclude(s => s.Sets)
    .Include(w => w.Segments)
        .ThenInclude(s => s.Exercise)
        .Include(w => w.BodyParts)
    .SingleOrDefaultAsync(w => w.Id == id);

workout.Segments = workout.Segments.OrderByDescending(x => x.Name);
foreach (var seg in workout.Segments)
{
    seg.Sets = seg.Sets.OrderByDescending(x => x.Name);
}
//Do same way for other includes.
1
1/19/2020 2:04:02 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow