Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between LINQ to Objects and LINQ to SQL queries

I have been using LINQ to query my POCO objects for some time, but I have not yet tried LINQ to SQL. I assume that LINQ to SQL queries are somehow converted to equivalent SQL queries and, given this, I am wondering if that affects the way LINQ to SQL queries are or should be written.

Are there any significant differences between LINQ to Objects and LINQ to SQL that affect how I should write a query for either?

like image 820
GraemeF Avatar asked Nov 11 '09 21:11

GraemeF


1 Answers

The main difference is as you say, LINQ to SQL queries are converted into SQL. That means that there is code you can write which isn't actually convertible or has some subtly different semantics - and you only find that out at execution time.

For example:

var query = from person in people
            where person.Age == person.GetHashCode()
            select person;

will compile fine, but fail at execution time because LINQ to SQL doesn't know what to do with GetHashCode().

Basically I find LINQ to SQL a lot harder to predict than LINQ to Objects. That's not to say it's not useful - it's just a slightly different world. MS has done an amazing job at letting you write queries which very often just do what you expect them to, but it can't do everything.

like image 100
Jon Skeet Avatar answered Oct 03 '22 04:10

Jon Skeet