views:

3031

answers:

4

Lets say you are working in SQL 2005 with a copy of Northwind database installed. Your working on an ASP.NET application with an Employees "browse" page. At the top of the page you have a "Title" filter where you would like to display these 5 choices in a dropdown:

[ALL]
Vice President, Sales
Sales Representative
Sales Manager
Inside Sales Coordinator

In T-SQL you would use something like the statement below to get your list.

SELECT DISTINCT Title FROM Employees ORDER BY Title

What is the best way of doing this in NHibernate? Assume that the initial database design is somewhat out of your control (just like Northwind)... Meaning that you won't be creating a Titles or Positions table for normalization.

Thanks.

A: 
criterion =  ... // SELECT Title FROM Employees ORDER BY Title
criterion.SetResultTransformer(new NHibernate.Transform.DistinctRootEntityResultTransformer())
Alex Reitbort
+1. but whats the ... part?
tyndall
be careful, result transformers actually filter the results *on the client*. Use a projection instead.
Mauricio Scheffer
@Bruno It's criterion for "SELECT Title FROM Employees ORDER BY Title". I am not near VS and I don't' remember the exact syntax.
Alex Reitbort
mausch, when you use a projection what kind of object is being returned? An anonymous-typed one? similar to LINQ?
tyndall
+1  A: 

There is another similar post that already has an accepted answer, probably check that out first:

http://stackoverflow.com/questions/318157/get-distinct-result-set-from-nhibernate-using-criteria-api

Brendan Kowitz
+1. This shows me at least I need to do some more reading on the NHibernate.Transform.DistinctRootEntityResultTransformer class. Not sure I follow the second post with the Projections. Off to do some research.
tyndall
A: 

ANSWER: I have 29 records in the table with 4 records repeated twice. I want only Distinct results. So, the total number of records should be 25.

below is test method

[TestMethod]
public void UserApplicationsTest()
{
    int usercount = 25;
    string query = "select from User u left outer join fetch u.ApplicationRequests ar";

    ISession session = NHibernateSessionManager.GetSession();


    IList<User> users = session.CreateQuery
       (
       query
       )
       .List<User>()
       .Distinct<User>().ToList();


    Assert.AreEqual(usercount, users.Count);

}
kalyan
Does this .Distinct<User>() call require the NH LINQ provider?
tyndall