James123
James123

Reputation: 11662

Dynamic where clause in LINQ?

I am trying to load data based on Dynamic where condition.

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

It is giving compilation error 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

How to handle this?

Upvotes: 3

Views: 7623

Answers (3)

Andrei
Andrei

Reputation: 56716

Where awaits conditions in form of lambdas rather than strings, so you have to refactor your code a little bit (just an idea below):

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

and later use it:

...
join b in query
...

Upvotes: 9

Jim Wooley
Jim Wooley

Reputation: 10418

The error you are seeing appears to indicate that you are using EF not LINQ to SQL. Please correct your tags if that is the case. If you want to use strings, consider using ObjectQuery's Where method instead of using DBSet. Alternatively, you could build the entire query using EntitySQL.

Upvotes: 0

Ehsan
Ehsan

Reputation: 32721

see this blog by Scott. It should help you sort your issue

Upvotes: 0

Related Questions