Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Linq to SQL and Linq to Objects queries the same?

If we abstract out the DataContext, then are L2S and L2O queries identical?

I already have a working prototype which demonstrates this, but it is very simple and wonder if it will hold up to more advanced querying.

Does anyone know?

like image 340
Duncan Avatar asked Jun 27 '09 09:06

Duncan


People also ask

What is difference between LINQ and SQL?

The main difference between LINQ and SQL is that LINQ is a Microsoft . NET framework component, which adds native data querying capabilities to . NET languages, while SQL is a standard language to store and manage data in RDBMS.

How LINQ queries converted into SQL queries?

LINQ to SQL translates the queries you write into equivalent SQL queries and sends them to the server for processing. More specifically, your application uses the LINQ to SQL API to request query execution. The LINQ to SQL provider then transforms the query into SQL text and delegates execution to the ADO provider.

Is Entity Framework same as LINQ to SQL?

LINQ to SQL allow you to query and modify SQL Server database by using LINQ syntax. Entity framework is a great ORM shipped by Microsoft which allow you to query and modify RDBMS like SQL Server, Oracle, DB2 and MySQL etc.

What is LINQ to SQL?

LINQ to SQL is a component of . NET Framework version 3.5 that provides a run-time infrastructure for managing relational data as objects. Relational data appears as a collection of two-dimensional tables (relations or flat files), where common columns relate tables to each other.


1 Answers

No they're not the same.

LINQ to Objects queries operate on IEnumerable<T> collections. The query iterates through the collection and executes a sequence of methods (for example, Contains, Where etc) against the items in the collection.

LINQ to SQL queries operate on IQueryable<T> collections. The query is converted into an expression tree by the compiler and that expression tree is then translated into SQL and passed to the database.

It's quite commonplace for LINQ to SQL to complain that a method can't be translated into SQL, even though that method works perfectly in a LINQ to Objects query. (In other cases, you may not see an exception, but the query results might be subtly different between LINQ to Objects and LINQ to SQL.)

For example, LINQ to SQL will choke on this simple query, whereas LINQ to Objects will be fine:

var query = from n in names
            orderby n.LastName.TrimStart(',', ' ').ToUpper(),
                    n.FirstName.TrimStart(',', ' ').ToUpper()
            select new { n.FirstName, n.LastName };

(It's often possible to workaround these limitations, but the fact that you can't guarantee that any arbitrary LINQ to Objects query will work as a LINQ to SQL query tells me that they're not the same!)

like image 125
LukeH Avatar answered Oct 20 '22 17:10

LukeH