views:

1336

answers:

1

If I were to select some rows based on certain criteria I can use ICriterion object in NHibernate.Criterion, such as this:

  public List<T> GetByCriteria()
  {
  SimpleExpression newJobCriterion =
    NHibernate.Criterion.Expression.Eq("LkpStatu", statusObject);
  ICriteria criteria = Session.GetISession().CreateCriteria(typeof(T)).SetMaxResults(maxResults);
  criteria.Add(newJobCriterion );
  return criteria.List<T>();
  }

Or I can use LINQ's where clause to filter what I want:

  public List<T> GetByCriteria_LINQ()
  {

  ICriteria criteria = Session.GetISession().CreateCriteria(typeof(T)).SetMaxResults(maxResults);

  return criteria.Where(item=>item.LkpStatu=statusObject).ToList();
  }

I would prefer the second one, of course. Because

  1. It gives me strong typing
  2. I don't need to learn yet-another-syntax in the form of NHibernate

The issue is is there any performance advantage of the first one over the second one? From what I know, the first one will create SQL queries, so it will filter the data before pass into the memory. Is this kind of performance saving big enough to justify its use?

+3  A: 

As usual it depends. First note that in your second snippet there is .List() missing right after return criteria And also note that you won't get the same results on both examples. The first one does where and then return top maxResults, the second one however first selects top maxResults and then does where.

If your expected result set is relatively small and you are likely to use some of the results in lazy loads then it's actually better to take the second approach. Because all entities loaded through a session will stay in its first level cache.

Usually however you don't do it this way and use the first approach.

Perhaps you wanted to use NHibernate.Linq (located in Contrib project ). Which does linq translation to Criteria for you.

Rashack