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

Please look at this snippet:

C#
var query = from t in db.ThingTable
             where t.Id == id
             select t;

if (!query.Any())
    return null;

ThingTable result = _Query.First();


LINQ to SQL isn't really my thing, but I have a question. Because (in my understanding) the query gets turned into an expression tree to be executed by SQL Server, is there any danger that the query will get executed twice - once for the Any() and once for First()? Or is it smart enough to reuse the result set?

Thanks.
Posted

This will work way faster!

var foundThingTable = db.ThingTable.FirstOrDefault(tt => tt.Id == id);
return foundThingTable;
 
Share this answer
 
Comments
Rob Philpott 26-Sep-13 5:15am    
Yes, agreed. What I'm interested in though is whether the code above goes to the DB twice. I'm analysing, not fixing!
I am not sure, if it is enough smart to reuse the result set, that's why I am using such querry:
C#
var query = (from t in db.ThingTable
             where t.Id == id
             select t).FirstOrDefault();
 
if (query == null)
    return null;
 
ThingTable result = query;

In this case you will get only one record that you need and no need to call First() to get first record.
 
Share this answer
 
v3
Comments
Eduard Keilholz 24-Sep-13 10:21am    
You're almost there but there's a bit of code not necessary here. In your code, you can skip everything from the if down and just return 'query'. Results in the same.
Alexander Dymshyts 24-Sep-13 10:25am    
I just remade his querry. May be he wants to make changes in that record and save it back to db, than he does not need to do return. If he needs to return record, than your solution is better.
Eduard Keilholz 24-Sep-13 10:27am    
But still, the if and the type conversion don't make sense.
Alexander Dymshyts 24-Sep-13 10:33am    
I agree about conversion. But if he wants to make change in a field, and save it back, then there will be error during saving to bd, if field marked as Not Null.
Eduard Keilholz 24-Sep-13 10:42am    
Alright, but why not
if (query != null){
query.property = "x";
db.SaveChanges();
}
using
if (blah)
return null;
creates an extra exit point for your method and therefore your method more complex without any reason

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