Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get List of Parent Entities with Child Count In Nhibernate QueryOver

I have two classes :

    public class Parent
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public ICollection<Child> Childrens { get; set; }
    }

    public class Child
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

Now through Nhibernate QueryOver I want to get list of all Parent with no of Count of children in single query.

Expected output is ?:

ParentId  Name ChildrenCount
1         ABC      10
2         CDE      5

can anyone help me .

like image 839
Moiz Avatar asked Nov 20 '15 11:11

Moiz


1 Answers

Using this DTO for projection:

public class ParentDto
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int ChildrenCount { get; set; }
}

Use this query:

Child childAlias = null;
ParentDto dto = null;

var dtoParents = Session.QueryOver<Parent>()
    .JoinAlias(x => x.Childrens, () => childAlias)
    .SelectList(list => list
        .SelectGroup(x => x.Id).WithAlias(() => dto.Id)
        .SelectGroup(x => x.Name).WithAlias(() => dto.Name)
        .SelectCount(() => childAlias.Id).WithAlias(() => dto.ChildrenCount))
    .TransformUsing(Transformers.AliasToBean<ParentDto>())
    .List<ParentDto>();

You can read more about QueryOver projections using DTOs here.

like image 84
Najera Avatar answered Sep 28 '22 15:09

Najera