Predicate with DapperExtensions

拈花ヽ惹草 提交于 2019-12-10 15:48:31

问题


Im trying to make a generic Find method with DapperExtensions

This is my method

 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);
        }
    }

But i get System.NullReferenceException on this row var predicate = Predicates.Field<T>(expression, Operator.Eq, true);

This is from the DapperExtensions help documentation But I try convert this to a Generic method.

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();
}

回答1:


I haven't repro'd, but it looks like the issue is, in part, that you are making the expression more complex than the example. As a suggestion, try:

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);
    }
}

and:

var data = Find(p => p.MarketId, marketId);

This is completely untested, based just on your comments and the example.

If your code-base doesn't make that practical, then I would suggest just try it with the above to see if that works, because there are ways of pulling apart an expression to extract those pieces. But it isn't worth giving an example of that until we know whether the above works.



来源:https://stackoverflow.com/questions/14585212/predicate-with-dapperextensions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!