Click here to Skip to main content
15,919,132 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All

I have a question regarding the behaviour of a linq query.

Consider the following query:

C#
var result = from c in dataContext.Customer
             where (!c.IsDeleted)
             select c;

As a test, I've deleted the "IsDeleted" field from the database without rebuilding the definitions (I'm testing my error handling). When I re-execute the query with the field deleted from the database, the statement doesn't produce an exception, it just skips over the statement and return nothing to the result variable.
However, when I add a .ToList() to the linq query, it produces an exception.

Can anybody exlpain why it only throws an exception if I add the .ToList() statement?
Posted
Updated 2-Dec-11 3:04am
v2
Comments
[no name] 2-Dec-11 9:05am    
EDIT: added "pre" and code block

SQL
var result = from c in dataContext.Customer
where (!c.IsDeleted)
select c;


This statement just creates a query, it is not executed until the ToList method is called. You could create the query in one part of your code and execute it in another, or execute it multiple times by calling ToList, or other methods.
 
Share this answer
 
Comments
HighOnFireZA 2-Dec-11 8:37am    
The funny thing is I assign a grid's datasource to the IQueryable result and it still doesn't throw the exception, the grid is just blank which I find strange.
Thanks anyway, I understand how it works now.
Because at that point you haven't actually executed the query, you've just prepared an Expression Tree (a 'query definition' if you like) of IQueryable

This means you can chain to the Expression, add additional clauses or whatever you require,

It's only when you call one of the methods such as ToList(), ToArray(), FirstOrDefault() ... etc... that the expression will actually be evaluated - in this case the Expression evaluates to SQL to execute against your data context
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900