tags:

views:

51

answers:

3

Is there a way in NHibernate to check if an object exists in the database without having to get/load the object?

A: 

From the Hibernate documentation:

Use Session.get() to test if a row exists in the db.

Remember: with lazy loading, your object won't be "loaded" anyway: Session.get() will generate the simplest select statement required to know if the object exists (select id from ... where ...), and returns a proxy object.

Samuel_xL
I should add than with this method, you can check if object != null in a lazy manner.
Rafael Belliard
This isn't correct, Get will always perform a Select against the database (or get the object from cache) and return the object if the record exists or null if it doesn't. You may be thinking of Load which always returns a proxy without hitting the database, so there is no guarantee that the record exists.
Jamie Ide
+1  A: 

I think you are looking for this...

var fooExists = session.Query<Foo>().Where(f => /*condition*/).Any()
Diego Mijelshon
+1  A: 

Could always do a count.

I tend to use DetachedCriteria, so I'd have something like:

var criteria = // some criteria that will identify your object

var result = criteria
    .GetExecutableCriteria(Session)
    .SetProjection(Projections.RowCountInt64())
    .UniqueResult();

return result > 0;
David