I have the following method. This returns a single unqiue order. However i just want the first result. What is the best way to achieve this. Of course i could return a List and then get the first result from that.
ie .List<Order>().SingleOrDefault();
Surely there is away through the criteria api to acheive this?
Model.Order order = _session
.CreateCriteria(typeof(Model.Order))
.Add(Restrictions.Eq("UserName", user.UserName))
.Add(Restrictions.Eq("CompanyId", companyId))
.Add(Restrictions.Eq("OrderStatus", OrderStatusHelper.OrderOpen()))
.AddOrder(sortOrder)
.UniqueResult<Model.Order>(); // results not always unique
It’s slightly less complicated than Saint Gerbil proposed:
This will do a query using the DB syntax for retrieving only one record.
If there are no records matching the criteria,
UniqueResultreturns null.You could also use NHibernate Linq (either the 2.x contrib provider, or the one integrated in NH 3.x). In that case, you should use
FirstOrDefaultinstead ofSingleOrDefaultto achieve the result you want.