NHibernate 3 - 类型安全的方式来选择不同的值列表

时间:2011-09-07 10:42:22

标签: nhibernate distinct

我试图在另一列上订购时从表中选择一个不同的值列表。

到目前为止,我唯一能使用魔术字符串和对象数组的东西。有更好的(类型安全)方式吗?

  var projectionList = Projections.ProjectionList();
  projectionList.Add(Projections.Property("FolderName"));
  projectionList.Add(Projections.Property("FolderOrder"));

  var list = Session.QueryOver<T>()
    .Where(d => d.Company.Id == SharePointContextHelper.Current.CurrentCompanyId)
    .OrderBy(t => t.FolderOrder).Asc
    .Select(Projections.Distinct(projectionList))
    .List<object[]>()
    .ToList();

  return list.Select(l => new Folder((string)l[0])).ToList();
顺便说一下,用linq做这个不行,你必须选择FolderOrder否则你会得到一个sql错误(ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

然后这样做会产生一个已知错误:Expression type 'NhDistinctExpression' is not supported by this SelectClauseVisitor.关于使用带有不同

的匿名类型
 var q = Session.Query<T>()
    .Where(d => d.Company.Id == SharePointContextHelper.Current.CurrentCompanyId)
    .OrderBy(d => d.FolderOrder)
    .Select(d => new {d.FolderName, d.FolderOrder})
    .Distinct();
  return q.ToList().Select(f => new Folder(f));

所有似乎都有很多箍和复杂性来做一些基础知识....

2 个答案:

答案 0 :(得分:2)

要解决类型安全问题,语法为:

  var projectionList = Projections.ProjectionList();
  projectionList.Add(Projections.Property<T>(d => d.FolderName));
  projectionList.Add(Projections.Property<T>(d => d.FolderOrder));

答案 1 :(得分:1)

object []事情是不可避免的,除非您定义一个特殊的类/结构来仅保留FolderNameFolderOrder
看到这个伟大的introduction to QueryOver类型安全,这肯定是支持的 祝你好运。