Sabby62
Sabby62

Reputation: 1717

Transform NHibernate QueryOver result to Dictionary

I have Nhibernate query that gives me back two columns (string and bool). I want to transform the result into a Dictionary. I know there are Transformers available but I am not sure how to get this working

Session.QueryOver<Customer>()
    .Where(x => x.Id == XXX)
    .Select(x => x.Name, x => x.Moderator)

Upvotes: 1

Views: 2691

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126072

I don't think there's a built in transformer that can do this (you could write your own), but it might be simple enough that writing a bit of LINQ after getting the query results back is good enough.

It depends on what you want your dictionary to look like, but here's an example that might help. Say you wanted to get a dictionary where the key is true or false, representing moderators and non-moderators, and the value is a List<string> with the names of the moderators. In that case you could write:

IDictionary<bool, List<string>> moderatorDictionary = session.QueryOver<Customer>()
    .Select(
        x => x.Name,
        x => x.Moderator
    )
    .List<object[]>()
    .GroupBy(x => (bool)x[1], x => (string)x[0])
    .ToDictionary(grp => grp.Key, grp => grp.ToList());

Using List<object[]> usually isn't great for maintainability, but for two properties like this it's probably okay. If you're working with more properties, it's best to create a class and use AliasToBean to transform each row into an instance of that class.

Upvotes: 0

Related Questions