Search code examples
c#nhibernategroup-byanonymous-typesqueryover

nhibernate projection to anonymous type


I have a query to get count of Child objects for a Parent object.
I need to convert the result into a List<KeyValuePair<int, int>>
Can't figure out.

Child childAlias = null;
Parent parentAlias = null;
int[] parentIds = new int[]{1,2,3};

var temp = sess.QueryOver<Parent>()
   .JoinQueryOver(p => p.Children, () => childAlias)
   .Where(c => c.Parent.Id.IsIn(parentIds))
   .Select(Projections.ProjectionList()
      .Add(Projections.GroupProperty(Projections.Property<Parent>(x => x.Id)))
      .Add(Projections.Count(() => childAlias.Id)))
  .List<object[]>();

I need this List<object[]> to be a List<KeyValuePair<int, int>>
I know it involves a Select with an annonymous object but can't figure out


Solution

  • Working query should look like this:

    Child childAlias = null;
    Parent parentAlias = null;
    int[] parentIds = new int[] {1, 2, 3};
    
    var temp = sess.QueryOver<Parent>()
        .JoinQueryOver(p => p.Children, () => childAlias)
        .WhereRestrictionOn(c => c.Parent.ID).IsIn(parentIds)
        .Select(Projections.ProjectionList()
            .Add(Projections.GroupProperty(Projections.Property<Parent>(x => x.ID)))
            .Add(Projections.Count(() => childAlias.ID)))
        .List<object[]>()
        .Select(x => new KeyValuePair<int,int>((int)x[0], (int)x[1]));