NHibernate. get singleOrDefault
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:
Model.Order order = _session
.CreateCriteria<Model.Order>()
.Add(Restrictions.Eq("UserName", user.UserName))
.Add(Restrictions.Eq("CompanyId", companyId))
.Add(Restrictions.Eq("OrderStatus", OrderStatusHelper.OrderOpen()))
.AddOrder(sortOrder)
.SetMaxResults(1)
.UniqueResult<Model.Order>();
This will do a query using the DB syntax for retrieving only one record.
If there are no records matching the criteria, UniqueResult
returns 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 FirstOrDefault
instead of SingleOrDefault
to achieve the result you want.
IList<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)
.SetMaxResults(1)
.List<Model.Order>(); // results not always unique
if(order.Count == 1)
{
return order[0];
}
else
{
return default(Model.Order)
}
Something like this.
精彩评论