Can an ICriteria return an IDictionary instead of a List<DTO>?

不问归期 提交于 2020-01-03 17:20:30

问题


Currently I can get this SetResultTransformer method to return a List of some arbitrary kind of DTO as follows:

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>();

where SomeDTO is defined as:

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

I think it's a little bit of an overkill having to create a type specifically to take the data out of this query though. Ideally, I could use a IDictionary<int,int>, because built into the framework. As it stands though, it seems I can return a List.

I thought I could throw a sneaky KeyValuePair<int,int> into the SetResultsTransformer, like this:

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>>();

but result is just an empty KeyValuePair. Is there any way for me to do this, or do I need the DTO?


回答1:


Use a client-side Linq projection. I do this all the time:

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



回答2:


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();

This should return IList<object[]> :)



来源:https://stackoverflow.com/questions/3463144/can-an-icriteria-return-an-idictionary-instead-of-a-listdto

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