简体   繁体   中英

LINQ query with multiple conditional where clauses

I can't seem to figure out how to make a LINQ query with where clauses based on multiple nullable variables work. I've tried the "if" methods I've seen on this site, and I get the error:

The name I doesn't exist in the current context.

The "Point" fields are formatted as "POINT(num1, num2)" and work fine in a SQL query.

query = from i in _db.ILV
        join p in _db.PC on
             i.PostCode equals p.PostCode                        
        select i;

if (!string.IsNullOrEmpty(key))
    query = query.Where(i = i.Description.Contains(key));

if(!string.IsNullOrEmpty(rng))
    query = query.Where(i => STGeomFromText(i.Point).STDistance(q.Point) <= rng);

if (!string.IsNullOrEmpty(cat))
    query = query.Where(i = i.CategoryID.ToInt(cat));

if(!string.IsNullOrEmpty(sub))
    query = query.Where(i = i.SubCategoryID.ToInt(sub));

return query;

That would work if you used i => instead of i = . You can put it all in one block however, like follows:

query = from i in _db.ILV
        join p in _db.PC on
            i.PostCode equals p.PostCode   
        where (!string.IsNullOrEmpty(key)) ? i.Description.Contains (key) : true &&
              (!string.IsNullOrEmpty(rng)) ? // rest of your where clauses follow the same pattern          
        select i;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM