Question

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;
Was it helpful?

Solution

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top