Usage of Expression to create generic query method for NHibernate

In my previous post about caching and generic query via NHibernate [https://csharptipstricks.blogspot.com/2019/12/caching-and-generic-query-using.html], there was a method that takes Expression as a parameter, as shown below:


// Check if a record exists or not
public async Task<bool> IsRecordExistsAsync<K>(Expression<Func<K, bool>> condition) where K : class
{
    bool isExist = await GetSession().QueryOver<K>()
                                     .Where(condition)
                                     .RowCountAsync() > 0;
    return isExist;
}

Initially, I had the intention of creating a common method which could produce an Expression that holds a Func<K, bool> delegate. The method is as follow:






public static Expression<Func<T, bool>> CreateCondition<T>(Func<T, bool> func)
{
  return x => func(x);
}

When I use the Expression produced via the method above as an input parameter for IsRecordExistsAsync, an exception was thrown because NHibernate could not determine the type through the Expression. It seems the generic method that I have created to convert the Func delegate was merely a caller to the delegate[1]
Based on my deduction, NHibernate was unable to determine the type because the Expression was a shell in which the body of the delegate is not known. Instead, the following way of building the expression was used[1]:
Expression<Func<BookStore, bool>> expression = x => x.BookID == "123";
[1] https://stackoverflow.com/questions/14907327/how-to-convert-funct-bool-to-expressionfunct-bool









Comments

Popular posts from this blog

ASP.NET Core service locator pattern

Caching and generic query using NHibernate [.NET Core]

Ways to perform eager loading via NHibernate