开发者

NHibernate 3 - type safe way to select a distinct list of values

开发者 https://www.devze.com 2023-04-03 18:12 出处:网络
I am trying to select a distinct list of values from a table whilst ordering on another column. The only thing working for me so far uses magic strings and an object array. Any better (type-safe) way

I am trying to select a distinct list of values from a table whilst ordering on another column.

The only thing working for me so far uses magic strings and an object array. Any better (type-safe) way?

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

btw, doing it with linq won't work, you must select FolderOrder otherwise you'll get a sql error (ORDER BY items must appear in the select list if SELECT DISTINCT is specified. )

and then doing that gives a known error : Expression type 'NhDistinctExpression' is not supported by this SelectClauseVisitor. regarding using anonymous types with distinct

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

All seems a lot of hoops and comp开发者_高级运维lexity to do some sql basics....


To resolve the type-safety issue, the syntax is:

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


the object [] thing is unavoidable, unless you define a special class / struct to hold just FolderName and FolderOrder.
see this great introduction to QueryOver for type-saftey, which is most certainly supported.
best of luck.

0

精彩评论

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