Pavlo
Pavlo

Reputation: 397

SQL to Nhibernate criteria

I have class ClassA mapped to table TableA. How to convert next sql to NHibernate criteria?

  SELECT DISTINCT t.Id, (Select COUNT(*) FROM TableA WHERE [Id] = t.Id)
  FROM TableA AS t

Update 1: TableA is a view indeed. It's for merging statistic from two tables. Id is not identity, just the field, sorry for ambiguity.

Upvotes: 0

Views: 254

Answers (1)

Oskar Berggren
Oskar Berggren

Reputation: 5647

From http://nhibernate.info/doc/nh/en/index.html#querycriteria-projection:

List results = session.CreateCriteria(typeof(ClassA))
    .SetProjection( Projections.ProjectionList()
        .Add( Projections.RowCount() )
        .Add( Projections.GroupProperty("Id") ) )
    .List();

Or with Linq:

from a in session.Query<ClassA>
group a by a.Id into g
select new { g.Key, g.Count())

Upvotes: 1

Related Questions