Results 1 to 2 of 2

Thread: How to create dynamic expressions in nHibernate without using Criteria API.

  1. #1
    Join Date
    Feb 2012
    Posts
    2

    Unhappy How to create dynamic expressions in nHibernate without using Criteria API.

    Hi,

    I have below method

    public IList<T> GetFiltered
    (
    int first, int maxresults,
    Expression<Func<T, bool>> where,
    Dictionary<Expression<Func<T, object>>, object> like,
    Expression<Func<T, object>> orderBy, bool? asc,

    out int count
    )
    {
    ITransaction transaction = null;
    try
    {
    ISession session = SessionProvider.Instance.CurrentSession;
    using (transaction = session.BeginTransaction())
    {
    var query = session.QueryOver<T>();

    // add where clause
    if (where != null)
    query = query.Where(where); //

    // add like clause
    if (like != null && like.Count > 0)
    foreach (var likeItem in like)
    query = query.WhereRestrictionOn(likeItem.Key).IsLike(like Item.Value);

    // build count query set to run in the future
    var query_count = query.Clone().ToRowCountQuery();
    var future_count = query_count.FutureValue<int>();

    // order by expression
    if (orderBy != null)
    {
    if (!asc.HasValue)
    asc = true;

    query = asc.Value ? query.OrderBy(orderBy).Asc : query.OrderBy(orderBy).Desc;
    }

    // pagination
    query.Skip(first);
    query.Take(maxresults);

    IList<T> entities = query.List();
    count = future_count.Value;

    transaction.Commit();

    return entities;
    }
    }
    catch (Exception)
    {
    if (transaction != null && transaction.IsActive)
    transaction.Rollback();

    throw;
    }
    }

    at the time of calling this function, i want to send more than one where clause like this:- where => where.Project.ID == 167 && where.ID > 200 && where.Status == 0.

    These where clause will decide at run-time based on some conditions like:

    foreach (var expression in SearchExpArray)
    {
    switch (expression.Key)
    {
    case "Name":
    Like.Add(like => like.Name, expression.Value + "%");
    break;
    case "Code":
    Like.Add(like => like.Code, expression.Value + "%");
    break;

    }} // Example of like criteria.

    I want the same like above for where clause too.

  2. #2
    Join Date
    Jul 2010
    Posts
    245

    Default

    You should post this question to the NHUSERS forum at http://groups.google.com/group/NHUSERS as its not SPRNET-related per se.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •