NHibernate QueryOver projection on many-to-one

前端 未结 1 1116
礼貌的吻别
礼貌的吻别 2021-01-24 16:10

I am trying to get a QueryOver working using a Projection on a many-to-one.

The class \"Post\" has a property many-to-one \"Creato

相关标签:
1条回答
  • 2021-01-24 16:40

    There is a solution, we can use projections for many-to-one and then custom result transformer.

    DISCLAIMER: I can read VB syntax but do not have enough courage to write... I expect that you can read C# and convert it into VB....

    So we can have projection like this:

    // aliases
    Post root = null;
    Creator creator = null;
    
    // projection list
    var columns = Projections.ProjectionList();
    
    // root properties
    columns.Add(Projections.Property(() => root.ID).As("ID"));
    columns.Add(Projections.Property(() => root.Text).As("Text"));
    
    // reference properties
    columns.Add(Projections.Property(() => creator.ID).As("Creator.ID"));
    columns.Add(Projections.Property(() => creator.FirstName).As("Creator.FirstName"));
    
    // so our projections now do have proper ALIAS
    // alias which is related to domain model 
    //  (because "Creator.FirstName" will be use in reflection)
    
    var query = session.QueryOver<Post>(() => root)
        .JoinAlias(() => root.Creator, () => creator)
        .Select(columns)
    

    Now we would need smart Transformer, our own custome one (plugability is power of NHibernate). Here you can find one:

    public class DeepTransformer

    And we can continue like this

    var list = query
        .TransformUsing(new DeepTransformer<Post>())
        .List<Post>()
    

    Check also this:

    • Fluent NHibernate - ProjectionList - ICriteria is returning null values
    • NHibernate AliasToBean transformer associations
    0 讨论(0)
提交回复
热议问题