Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional shortcuts in LinqToSql query

Here's a little LinqToSql GOTCHA:

// Returns the number of counties in a state, 
// or all counties in the USA if the state is null
public static int CountCounties(State s) {
  var q = 
    from cy in County.GetTable() // my method to get the ITable
    where (s == null || s.Code == cy.StateCode) // shortcut OR operator, right...?
    select cy;
  return q.Count();
}

Guess what - if you pass a null State object to this method, you get a null reference exception! It seems that LinqToSql doesn't use the || shortcut operator as a shortcut!

Answer credit goes to whoever proposes the best explanation & workaround for this.

like image 698
Shaul Behr Avatar asked Dec 06 '09 10:12

Shaul Behr


People also ask

What allows adding some conditional filters to the query in LINQ?

You can add additional Where constraints based on a condition in two ways: With a lambda expression. With WhereIf extenstion method.

What is LINQ query syntax?

LINQ query syntax is consist of a set of query keywords defined into the . NET Framework version 3.5 or Higher. This allows the programmer or developers to write the commands similar to SQL style in the code(C# or VB.NET) without using quotes. It is also know as the Query Expression Syntax.

What is method syntax and query syntax in LINQ?

Query syntax and method syntax are semantically identical, but many people find query syntax simpler and easier to read. Some queries must be expressed as method calls. For example, you must use a method call to express a query that retrieves the number of elements that match a specified condition.


2 Answers

If it's linq to sql then remeber that Linq is just parsing your query into SQL.

It is therefore sending both of your where clauses to the database, hence the exception. I dont find this surprising really, though it is arguably wrong.

You will just have to do an independant check.

if (!string.isNullOrEmpty(state.statecode)
     q = q.where( s => s.code == state.statecode
like image 149
Paul Creasey Avatar answered Sep 26 '22 14:09

Paul Creasey


This is not related to LINQ in general. In this case, the LINQ-to-SQL provider tries to parse the your lambda expression and make it a TSQL query. It cannot make too many assumptions based on your expression since it's trying to delegate most of the work to the database.

Long story short, the provider simply cannot translate it to SQL.

like image 45
Bryan Menard Avatar answered Sep 25 '22 14:09

Bryan Menard