Linq表达式IEnumerable<TEntity>不包含where的定义。

5

如何编写正确的Linq表达式,用于泛型“where”条件

public static class ConStr
{
    public static MySqlConnection Conn()
    {
        return new MySqlConnection(ConfigurationManager.ConnectionStrings["DBCN"].ConnectionString);
    }

}

Repositor.cs

private IDbConnection cn;

public IEnumerable<TEntity> FilterBy(Expression<Func<TEntity, bool>> expression)
{
     using(cn = ConStr.Conn())
     {
        return cn.GetAll<TEntity>(null).Where(expression); <--error does not contain definition of where
     }

 }

但是使用Linq表达式将会运行。
using (IDbConnection cn = ConStr.Conn()) 
{
    var que = cn.GetAll<Cause>(null).Where(x=>x.cause_id == 1);            
    bool dbIE = Utils.IsAny<Cause>(que);
    if (dbIE == true)
    {
        DGRID.DataSource = que;
    }
    else 
    {
        MessageBox.Show("Sorry No Value");
    }
}  

你可以将所有项放入List集合中,而不是实现IEnumerable接口。List集合本身就是IEnumerable,因此您无需编写自己的实现。 - jdweng
@IvanStoev 哦,我明白了,非常感谢。我会尝试进行更改。 - jake talledo
请注意,由于在返回IQueryable<T>实现时连接已关闭,因此您的FilterAll方法很可能无法正常工作。 - casperOne
@casperOne 这取决于 GetAll 扩展是如何实现的。 - Maxim Kosov
@maxim 请查看我基于以下版本所做的评论:http://stackoverflow.com/revisions/36810185/3 - casperOne
显示剩余2条评论
1个回答

4

IEnumerable<T> 没有包含带有 Expression 的重载方法。如果要使用带有 ExpressionWhere,必须将 GetAll 的结果更改为 IQueryable。对于您的特定情况,您只需将 Expression<Func<TEntity,bool>> expression 更改为 Func<TEntity,bool> expression,然后一切都应该正常工作。


感谢您的提问。Func<TEntity,bool>表达式适用于IEnumerable<T>,而for适用于IQueryable<T>。因此,表达式为Expression<Func<TEntity,bool>>。 - jake talledo
1
IEnumerable<T> 类型上还有 AsQueryable() 扩展方法,它可以将你的 IEnumerable 强制转换为 IQueryable,但我不太清楚为什么你要在生产环境中使用它。大多数情况下,简单的 FuncAction 就足够了,如果你想使用 Expression,你需要知道为什么。 - Maxim Kosov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接