将自定义查询映射到nHibernate中的对象

时间:2013-09-16 19:16:39

标签: sql nhibernate

请看一下这个例子:

Is it possible to call a stored procedure using NHibernate which returns a custom object instead of domain object?

假设我的结构有这个定义:

public class YourDto
{
    public int YourDtoId { get; set; }
    public string YourDtoTitle { get; set; }
    public List<YourDtoBook> YourDtoList { get; set; }
}

现在让我们假设我有一个这样的查询:

select yourColumn1 as YourDtoId, yourColumn2 as YourDtoTitle,
yourColumn3 as YourDtoList from YOUR_TABLE

此查询的结果如下:

YourDtoId| YourDtoTitle| YourDtoList
_____________________________________
1        |Jeff         | book1
1        |Jeff         | book2
2        |Kurt         | book3
2        |Kurt         | book4

如何正确映射这些实体? (即两个对象,每个对象有两个列表)

1 个答案:

答案 0 :(得分:0)

对映射类使用QueryOver使用Fetch Eager。

直接向DTO使用GroupBy:

var result = yourNhSession.CreateSQLQuery(@"
                select yourColumn1 as YourDtoId, yourColumn2 as YourDtoTitle,
                yourColumn3 as YourDtoList from YOUR_TABLE")
                .List<object[]>()
                .GroupBy(x => new
                {
                    YourDtoId = (int) x[0],
                    YourDtoTitle = (string) x[1]
                })
                .Select(x => new YourDto
                {
                    YourDtoId = x.Key.YourDtoId,
                    YourDtoTitle = x.Key.YourDtoTitle,
                    YourDtoList = x.Select(y => new YourDtoBook
                    {
                        Name = (string)y[2]
                    }).ToList()
                });

    public class YourDto
    {
        public int YourDtoId { get; set; }
        public string YourDtoTitle { get; set; }
        public List<YourDtoBook> YourDtoList { get; set; }
    }

    public class YourDtoBook
    {
        public string Name { get; set; }
    }