开发者

How can one check with NHibernate if there is already an object in the database with the given id?

开发者 https://www.devze.com 2022-12-12 01:05 出处:网络
My question is simple, given an ID (and the object type, of 开发者_Go百科course) what is the best way to check whether this ID is present in the database using NHibernate?

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

Thanks.


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;


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

0

精彩评论

暂无评论...
验证码 换一张
取 消