Morten Holmgaard
Morten Holmgaard

Reputation: 7806

nHibernate query result in duplicate queries when profiling (select top 1)

I am using nHibernate and it works fine.
But I started profiling it with miniprofiler and found that der where a lot of duplicate requests.

For instance this log message:

select TOP (1)  user0_.Id as Id26_
              , user0_.Username as Username26_
              , user0_.Password as Password26_
              , user0_.IsSystemAdmin as IsSystem4_26_
              , user0_.LastLogin as LastLogin26_
              , user0_.Name as Name26_
              , user0_.Email as Email26_
              , user0_.PhoneNumber as PhoneNum8_26_ 
from [User] user0_ 
where user0_.Username = @p0 

(ExecuteReader GetResultSet DoQuery DoQueryAndInitializeNonLazyCollections DoList ListIgnoreQueryCache List List List PerformList)

But the query is actually not a Top 1 query. There is one of those request for each row in the table, but it is supposed to be evaluated in on db query!

_userRepository.FindAllQuery(x => x.Username == username).FirstOrDefault();

public IQueryable<TEntity> FindAllQuery(Expression<Func<TEntity, bool>> expression)
{
    return Session.Query<TEntity>().Where(expression);
}

This might be releated but I am not sure:
http://charlass.wordpress.com/2012/03/11/nhibernate-firstordefault-and-fetch-not-what-i-expect/

Any clue on this?

Upvotes: 0

Views: 206

Answers (1)

Jonas J&#228;mtberg
Jonas J&#228;mtberg

Reputation: 571

By calling .FirstOrDefault() you instruct NHibernate to construct a TOP 1 query.

Upvotes: 2

Related Questions