1

请看一下这个例子:

是否可以使用返回自定义对象而不是域对象的 NHibernate 调用存储过程?

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

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

我该怎么做才能正确映射这些实体?(即两个对象,每个对象有两个列表)

4

1 回答 1

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; }
    }
于 2013-09-20T22:49:46.717 回答