NHibernate QueryOver projection on many-to-one

陌路散爱 提交于 2019-12-02 04:34:46
Radim Köhler

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:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!