动态 where 子句 lambda 或 C# 中的查询

本文关键字:查询 where 子句 lambda 动态 | 更新日期: 2023-09-27 18:37:13

>我正在尝试编写动态lambda或查询,但它发生了错误。

对于λ;我创建了一个函数

    public IEnumerable<musteriler>  GetCustomers<musteriler>(Expression<Func<musteriler, bool>> where)
   {
    IEnumerable<musteriler> _musteriler = market.musteriler.Where(where).Select(m => m);
     return _musteriler;
    }

我这样打电话

  IEnumerable<musteriler> _musteriler  = helper.GetCustomers<musteriler>(m => m.MAktif == true);

我在"在哪里(在哪里)"中得到两个错误,它们是

    The best overloaded method match for System.Data.Objects.ObjectQuery<AkilliMarket.musteriler>.Where(string, params System.Data.Objects.ObjectParameter[])' has some invalid arguments

   Argument 1: cannot convert from 'System.Linq.Expressions.Expression<System.Func<musteriler,bool>>' to 'string'

在我尝试了这样的字符串查询之后

 IEnumerable<musteriler> _musteriler=  market.musteriler.Where("MAktif = true").Select(m => m) as IEnumerable<musteriler>;

是的,它可以工作,但我不能使用 _musteriler..例如,当我写_musteriler时。计数();我收到此错误

  'MAktif' could not be resolved in the current scope or context. Make sure that all referenced variables are in scope, that required schemas are loaded, and that namespaces are referenced correctly. Near simple identifier, line 6, column 1.

MAktif 是我在 db 中的 musteriler 表的列名,我尝试了另一列,但结果相同。.

我犯了哪里的错误?

动态 where 子句 lambda 或 C# 中的查询

问题是IQueryable<T>.Where是一个扩展方法,并且在考虑扩展方法之前ObjectQuery.Where被选为"最佳重载方法匹配"。

尝试:

public IEnumerable<AkilliMarket.musteriler> GetCustomers<AkilliMarket.musteriler>(Expression<Func<AkilliMarket.musteriler, bool>> predicate)
{
   return market.musteriler.AsQueryable().Where(predicate);
}
public IEnumerable<musteriler>  GetCustomers<musteriler>(Expression<Func<musteriler, bool>> predicate)
       {
        return market.musteriler.AsQueryable().Where(predicate).AsEnumerable();
        }

如果它不起作用

你能试试吗

 var _musteriler=  market.musteriler.Where("it.MAktif = @val", new ObjectParameter("val", true)).AsEnumerable().Count();
如果

它有效,你的方法应该是(如果仍然有意义地制定一个方法)

public IEnumerable<musteriler> GetCustomers(string whereClause, params ObjectParameter[] parameters) {
   return market.musteriler.Where(whereClause, parameters).AsEnumerable(); 
}

我想你需要在代码的开头添加这个:

using System.Linq;

看起来你的市场是ObjectContext的,而 musteriler 是ObjectSet的,它不提供接受 lambda 的 Where - 你需要扩展 Where 方法,IQueryable接受 lambda 表达式。

在我尝试的示例中,我收到错误,

方法"Where"没有重载需要 3 个参数

使用我的where子句表达式使用SQLParametera。

我发现我需要

使用System.Linq.Dynamic; 一旦我发现它,DUH