使用DapperExtensions进行谓词化

Nil*_*ers 4 c# dapper

我试图用DapperExtensions创建一个通用的Find方法

这是我的方法

 public IEnumerable<T> Find(Expression<Func<T, object>> expression)
    {
        using (IDbConnection cn = GetCn())
        {
            cn.Open();

            var predicate = Predicates.Field<T>(expression, Operator.Eq, true);
            return cn.GetList<T>(predicate);
        }
    }
Run Code Online (Sandbox Code Playgroud)

但我接受System.NullReferenceException了这一行 var predicate = Predicates.Field<T>(expression, Operator.Eq, true);

这是来自DapperExtensions帮助文档但我尝试将其转换为Generic方法.

using (SqlConnection cn = new SqlConnection(_connectionString))
{
    cn.Open();
    var predicate = Predicates.Field<Person>(f => f.Active, Operator.Eq, true);
    IEnumerable<Person> list = cn.GetList<Person>(predicate);
    cn.Close();
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 5

我没有重新编写,但看起来问题部分在于你使表达式比示例更复杂.作为建议,请尝试:

public IEnumerable<T> Find<TValue>(Expression<Func<T, TValue>> expression,
                                   TValue value)
{
    using (IDbConnection cn = GetCn())
    {
        cn.Open();

        var predicate = Predicates.Field<T>(expression, Operator.Eq, value);
        return cn.GetList<T>(predicate);
    }
}
Run Code Online (Sandbox Code Playgroud)

和:

var data = Find(p => p.MarketId, marketId);
Run Code Online (Sandbox Code Playgroud)

这完全未经测试,仅基于您的评论和示例.

如果你的代码库没有那么实用,那么我建议你尝试使用上面的代码来看看它是否有效,因为有一些方法可以拆分表达式以提取这些部分.但是,在我们知道上述是否有效之前,不值得举一个例子.