带有DapperExtensions的谓词 [英] Predicate with DapperExtensions

查看:81
本文介绍了带有DapperExtensions的谓词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用DapperExtensions创建通用的Find方法

Im trying to make a generic Find method with DapperExtensions

这是我的方法

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

但是我得到了 System。此行上的NullReferenceException var predicate = Predicates.Field< T>(expression,Operator.Eq,true);

这来自DapperExtensions帮助文档
,但是我尝试将其转换为通用方法。

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


推荐答案

我没有复制 d,但看起来就像问题在某种程度上是使表达式比示例更复杂。作为建议,尝试:

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

和:

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

仅根据您的评论和示例,这是完全未经测试的。

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

如果您的代码库不实用,那么我建议您使用上面的代码 try ,看看是否有效,因为有多种方法可以将表达式分开以提取这些片段。但是在我们不知道上述方法是否有效之前,不值得举一个例子。

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.

这篇关于带有DapperExtensions的谓词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆