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
2010-08-19 20:23:25
I should add than with this method, you can check if object != null in a lazy manner.
Rafael Belliard
2010-08-19 21:01:50
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
2010-08-21 12:29:34
+1
A:
I think you are looking for this...
var fooExists = session.Query<Foo>().Where(f => /*condition*/).Any()
Diego Mijelshon
2010-08-19 23:15:55
+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
2010-08-24 00:27:33