nHibernate - 通过子集合拆分查询结果

时间:2014-02-12 07:45:03

标签: c# nhibernate collections

我有两个课程(实际上更多):

public class City{
  public string Name;
  public List<Street> Street;
}
public class Street{
  public string Name;
  public City City;
}

我正在尝试使用ICriterion检索过滤后的数据,大概如下:

ICriteria crit = CurrentSession
                .CreateCriteria(typeof (City));
crit = crit.CreateAlias("Streets", "Street", NHibernate.SqlCommand.JoinType.LeftOuterJoin);
crit.Add(Expression.InsensitiveLike("Name", "London", MatchMode.Exact));
crit.Add(Expression.InsensitiveLike("Street.Name", "Pic%", MatchMode.Exact));

我应该如何形成标准以将结果作为包含Street的子集合的City列表,只包含一个元素? 所以我需要得到下一个结果:

City: 'London' -> Streets:{'Piccadilly'}
City: 'London' -> Streets:{'Pickard'}
City: 'London' -> Streets:{'Pickwick'}

等。 但是现在我得到了:

City: 'London' -> Streets:{'Piccadilly', 'Pickard', 'Pickwick'}
City: 'London' -> Streets:{'Piccadilly', 'Pickard', 'Pickwick'}
City: 'London' -> Streets:{'Piccadilly', 'Pickard', 'Pickwick'}

行数=找到的街道数。我需要像“跨所有行的街道取消组合”这样的东西

1 个答案:

答案 0 :(得分:0)

我不鼓励使用City作为结果集,因为它不是有效的城市对象。

ICriteria crit = CurrentSession.CreateCriteria(typeof(City))
    .CreateAlias("Streets", "Street", JoinType.InnerJoin)
    .Add(Expression.InsensitiveLike("Name", "London", MatchMode.Exact))
    .Add(Expression.InsensitiveLike("Street.Name", "Pic%", MatchMode.Exact))
    .SetProjection(Projections.List()
        .Add(Projections.Property("Name"))
        .Add(Projections.Property("Street.Name")));


var results1 = crit.List<object[]>()
    .Select(arr => new LocationDto
                   {
                       CityName = (string)arr[0],
                       StreetName = (string)arr[1]
                   });

// or if it is really needed
var results2 = crit.List<object[]>()
    .Select(arr => new City
                   {
                       Name = (string)arr[0],
                       Streets = { new Street((string)arr[1]) }
                   });