开发者

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

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?


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


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[]> :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜