Question

here is my situation,I want to use a generic reposity to query data,here is the code:

public T SingleOrDefault(Expression<Func<T, bool>> filter)
{
    return Transact(() => session.QueryOver<T>().Where(filter).List().FirstOrDefault());
}   
protected virtual TResult Transact<TResult>(Antlr.Runtime.Misc.Func<TResult> func)
{
    try
    {
        if (!session.Transaction.IsActive)
        {
            TResult result;
            using (var tr = session.BeginTransaction())
            {
                result = func.Invoke();
                tr.Commit();
            }
            return result;
        }
        return func.Invoke();
    }
    catch (Exception e)
    {
        Log.Error(e);
        throw new Exception(e.Message);
    }
} 

but when I use the method such as:

Expression<Func<User,bool>> filter = user => String.Compare(user.Name, “TommyLike”, System.StringComparison.OrdinalIgnoreCase) == 0;
var result = _kernel.Get<IReposity<User>>.SingleOrDefault(filter)

it seems that can not recognise the var user in the filter,but when i change the filter to:

filter = user => user.Name == "TommyLike"

it runs ok,does anybody know how it does't work in the first try?and how to fix the problem?

Was it helpful?

Solution

QueryOver support that with this syntax:

var user = session.QueryOver<User>()
    .WhereRestrictionOn(x => x.Name).IsInsensitiveLike("TommyLike")

This must work:

public T SingleOrDefault(Func<IQueryOver<T, T>, IQueryOver<T, T>> filter)
{
    return Transact(() =>
    {
        var query = session.QueryOver<T>();

        query = filter(query);

        return query.SingleOrDefault();
    });
}

Calling it is almost the same:

var result = _kernel.Get<IReposity<User>>.SingleOrDefault(
    query => query.WhereRestrictionOn(x => x.Name).IsInsensitiveLike("TommyLike"));

OTHER TIPS

NHibernate linq provider does not support this case :

String.Compare(user.Name, “TommyLike”, System.StringComparison.OrdinalIgnoreCase) == 0

Not all .net methods can be translated to sql, however it is possible to make registrations for your own methods

http://sentinel101.wordpress.com/2010/12/30/extend-nhibernate-linq-for-regex-matching/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top