views:

37

answers:

2

Dear ladies and sirs.

My question is simple, given an ID (and the object type, of course) what is the best way to check whether this ID is present in the database using NHibernate?

Thanks.

+1  A: 

Using the ICriteria interface of nhibernate something like this

Session.CreateCriteria(typeof(User))  
    .Add(Expression.Eq("Id", 1))  
    .List<User>();

or

Session.CreateCriteria(typeof(User))  
  .Add(Expression.IdEq(1))  
  .List<User>();

or

IList<int> recs = Session.CreateCriteria(typeof(User))  
.SetProjection(Projections.Count("UserId"))  
.Add(Expression.IdEq(1))  
.List<int>();

recs.Count;
Nathan Fisher
A: 

I assume without retrieving the object? something like this...

bool exists = session.CreateCriteria<YourObject>()
    .SetProjection(Projections.Constant(1))
    .Add(Restrictions.IdEq(id))
    .UniqueResult != null;

for your standard null check on select 1 from YourObjectTable where id = @id

dotjoe