How to get a list of parents with the number of children 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 a list of all parents without the number of children in one query.

Expected Result:?:

ParentId  Name ChildrenCount
1         ABC      10
2         CDE      5

can someone help me.

+4
source share
1 answer

Using this DTO for design:

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 learn more about projections QueryOverusing the DTO here .

+4
source

Source: https://habr.com/ru/post/1616724/


All Articles