1

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;
2
  • What flavor of LINQ are you using (EF/L2S)? Where is STGeomFromText and STDistance declared? where is q declared? Commented Mar 4, 2014 at 22:02
  • I'm using Visual Studio 2013 .Net Framework 4.5. STGeomFromText and STDistance are methods in the System.Spatial.Geography class, and q is declared prior to the linq query as: q = from z in _db.PC where(z.PostCode == zip) select z; Commented Mar 4, 2014 at 22:48

1 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

4 Comments

I think it looks better like this: where (string.IsNullOrEmpty(key) || i.Description.Contains(key)) && (string.IsNullOrEmpty(rng) || .....) &&
As long as you are ANDing the conditions, I prefer the IO's option of using deferred execution to build the query rather than bloating the query with evaulations that the database may or may not need to do which can slow down the query at the database level with large tables. You are correct about using => vs = however.
That worked! Thank you, Andrew! BTW, I tried using i => and i == and it gave the same error as i =.
In case where i need to set multiple querys, for strings and Ids, how can I do that?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.