Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

EntityFramework. order by count of sub array elements

I created three tables in Database using Entity Framework

class User{
    public string Name {get;set;}
    public IEnumerable<Pet> Pets {get;set;}
}
class Pet{
    public string Name {get;set;}
    public IEnumerable<Toy> Toys {get;set;}
}
class Toy{
    public string Name {get;set;}
}

I want to select top 10 users (using linq) which have the biggest amount of toys.

Tried this one, but did not work. Entity framework could not translate it into SQL query

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Entities
.OrderBy(u => u.Pets.Select(n => n.Toys.Count()))
.ToListAsync();

What kind of linq query should I use to do this ?

>Solution :

I would suggest to prepare grouping query with totals:

var totals =
    from e in Entities
    from p in e.Pets
    from t in p.Toys
    group e by e.Id into g
    select new 
    {
        Id = g.Key,
        Count = g.Count()
    };

var query = 
    from e in Entities
    join t in totals on e.Id equals t.Id
    orderby t.Count descending
    select e;

var result = await query
    .Take(10)
    .ToListAsync();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading