LINQ中的动态where子句?

时间:2013-07-22 13:57:47

标签: c# linq linq-to-sql

我正在尝试根据Dynamic where条件加载数据。

string tempQry = string.Empty;
if (!string.IsNullOrEmpty(cusid) && !string.IsNullOrEmpty(mktid))
    tempQry = "x=>x.MarketID==" + mktid + "&& x.MasterCustomerID==" + cusid;
if (string.IsNullOrEmpty(cusid)) 
    tempQry = "x=>x.MarketID==" + mktid;
if (string.IsNullOrEmpty(mktid)) 
    tempQry = "x=>x.MasterCustomerID==" + cusid;

_lstOptInInterest = new LinkedList<OptInInterestArea>(
        (from a in _lstOptInInterest
         join b in _marketoEntities.CustCommPreferences.Where(tempQry)
         on new { CODE = a.Code, SUBCODE = a.SubCode } equals new { CODE = b.Option_Short_Name, SUBCODE = b.Option_Short_Subname }
         into leftGroup
         from b in leftGroup.DefaultIfEmpty()
         select new OptInInterestArea()
         {
             Code = a.Code,
             SubCode = a.SubCode,
             SubCodeDescription = a.SubCodeDescription,
             CodeDescription = a.CodeDescription,
             PrevOptIn = b != null && b.OptedIn == true
         }).ToList());

它给出了编译错误Where(tempQry)

'System.Data.Entity.DbSet<Market.Data.CustCommPreference>' does not contain a definition for 'Where' and the best extension method overload 'System.Linq.Queryable.Where<TSource>(System.Linq.IQueryable<TSource>, System.Linq.Expressions.Expression<System.Func<TSource,bool>>)' has some invalid arguments

如何处理?

3 个答案:

答案 0 :(得分:9)

Where等待lambda而不是字符串形式的条件,所以你必须稍微重构你的代码(下面只是一个想法):

IQueryable<CustCommPreference> query = _marketoEntities.CustCommPreferences.AsQueryable();
if (!string.IsNullOrEmpty(cusid)) 
    query = query.Where(x => x.MasterCustomerID == cusid);
if (!string.IsNullOrEmpty(mktid)) 
    query = query.Where(x => x.MarketID == mktid);

以后再使用它:

...
join b in query
...

答案 1 :(得分:0)

Scott查看此博客。它应该可以帮助您解决问题

答案 2 :(得分:0)

您看到的错误似乎表明您使用的是EF而不是LINQ to SQL。如果是这种情况,请更正您的标签。如果要使用字符串,请考虑使用ObjectQuery's Where方法而不是使用DBSet。或者,您可以使用EntitySQL构建整个查询。