Criteria可以返回Dictionary而不是List <dto>吗?</dto>

时间:2010-08-11 21:51:34

标签: c# nhibernate

目前我可以使用这个SetResultTransformer方法返回一些任意类型的DTO的List,如下所示:

var result = _session.CreateCriteria<Company>()
    .Add(Restrictions.In(groupCompanyInfo, (int[])groups.Select(xx => xx.Id).ToArray()))
    .SetProjection(Projections.ProjectionList()
        .Add(Projections.GroupProperty(groupCompanyInfo), "CompanyInfoGroupID")
        .Add(Projections.RowCount(), "TotalNumberOfCompanies"))
    .SetResultTransformer(Transformers.AliasToBean<SomeDTO>())
    .List<SomeDTO>();

其中SomeDTO定义为:

public class SomeDTO
{
    public int GroupId { get; set; }
    public int CountOfCompaniesInGroup { get; set; }
}

我认为,为了从这个查询中获取数据,我必须创建一个专门的类型。理想情况下,我可以使用IDictionary<int,int>,因为内置于框架中。尽管如此,似乎我可以返回一个List。

我以为我可以偷偷偷偷地KeyValuePair<int,int>加入SetResultsTransformer,就像这样:

var result = _session.CreateCriteria<Company>()
    .Add(Restrictions.In(groupCompanyInfo, (int[])groups.Select(xx => xx.Id).ToArray()))
    .SetProjection(Projections.ProjectionList()
        .Add(Projections.GroupProperty(groupCompanyInfo))
        .Add(Projections.RowCount())) // note, I removed the aliases
    .SetResultTransformer(Transformers.AliasToBean<KeyValuePair<int, int>>())
    .List<KeyValuePair<int, int>>();

result只是一个空的KeyValuePair。我有什么方法可以做到这一点,还是我需要DTO?

2 个答案:

答案 0 :(得分:5)

使用客户端Linq投影。我一直这样做:

var result = _session.CreateCriteria...
             .List<object[]>
             .ToDictionary(x => (int)x[0], x => (int)x[1]);

答案 1 :(得分:0)

var result = _session.CreateCriteria<Company>()
    .Add(Restrictions.In(groupCompanyInfo, (int[])groups.Select(xx => xx.Id).ToArray()))
    .SetProjection(Projections.ProjectionList()
        .Add(Projections.GroupProperty(groupCompanyInfo))
        .Add(Projections.RowCount())) // note, I removed the aliases
    .List();

这应该返回IList<object[]>:)

相关问题