How to partially project a child object with many fields in nHibernate

后端 未结 1 1740
离开以前
离开以前 2020-11-29 12:14

I have the following nHibernate query that select a course based on its course id and then return selected fields for the course object on the initial fetch

相关标签:
1条回答
  • 2020-11-29 12:39

    We can indeed use custom transformer. There is one, which I am using for a really very very deep projections (inlcuding dynamic objects - 5.1.13. component, dynamic-component)

    • DeepTransformer<TEntity>

    Take it (if needed adjust it) and your final query could be like this

    // just the last lines are different
    var query = session.QueryOver<CourseItem>()
        .JoinAlias(c => c.Teacher, () => teacherAlias)
        .Where(c => c.CourseID.IsInsensitiveLike(strNumber, option))
        .SelectList(list => list
               .Select(c => c.CourseID).WithAlias(() => courseAlias.CourseID)
               .Select(c => c.IsActive).WithAlias(() => courseAlias.IsActive)
               .Select(c => c.CourseDesc).WithAlias(() => courseAlias.CourseDesc)
    
               // the native WitAlias would not work, it uses expression
               // to extract just the last property
               //.Select(c => c.Teacher.ID).WithAlias(() => courseAlias.Teacher.ID)
               //.Select(c => c.Teacher.Name).WithAlias(() => courseAlias.Teacher.Name))
    
               // so we can use this way to pass the deep alias
              .Select(Projections.Property(() => teacherAlias.ID).As("Teacher.ID"))
              .Select(Projections.Property(() => teacherAlias.Name).As("Teacher.Name"))
    
               // instead of this
               // .TransformUsing(Transformers.AliasToBean<CourseItem>())
               // use this
               .TransformUsing(new DeepTransformer<CourseItem>())
    

    And in case, that your aliases do match to property names, that transformer will built the object tree...

    0 讨论(0)
提交回复
热议问题