Mun
Mun

Reputation: 14308

Handling null values in NHibernate LINQ

I've got an NHibernate query that looks like this:

var users = from u in _session.Query<User>();
            select new
                   {
                       u.FirstName
                       u.LastName,
                       u.UserGroups.FirstOrDefault(x => x.Group.GroupId == id).EmailAddress
                   }

However, if the user does not have a group with the specified ID, instead of defaulting the EmailAddress property to null, NHibernate throws the following error:

Exception of type 'Antlr.Runtime.NoViableAltException' was thrown [.Select[MyProject.Data.Entities.User,<>f__AnonymousType0`3[ ...[Snipped]

It seems to be choking on the missing UserGroup entity.

If I modify this query so that a new UserGroup entity is created if one wasn't found (shown below), it stops the error from occurring and the data is returned, but seems like a hack when I actually just want this to default to null (as it would in Entity Framework) without having to instantiate a new UserGroup object.

var users = from u in _session.Query<User>();
            select new
                   {
                       u.FirstName
                       u.LastName,
                       EmailAddress = (u.UserGroups.FirstOrDefault(x => x.Group.GroupId == id) ?? new UserGroup()).EmailAddress
                   }

Is there any way to achieve this?

Upvotes: 0

Views: 927

Answers (1)

Felipe Oriani
Felipe Oriani

Reputation: 38608

Try this:

var users = (from u in _session.Query<User>();
            select new
                   {
                       u.FirstName
                       u.LastName,
                       EmailAddress = u.UserGroups.Where(x => x.Group.GroupId == id)
                                                  .Select(x => x.EmailAddress)
                                                  .FirstOrDefault()
                   }).ToList();

First you add the condition with Where method, after this you change the output with Select method to get only the EmailAddress column and finally you call FirstOrDefault.

Remember to check if EmailAddress is not null before using it.

Upvotes: 1

Related Questions