ObjectQuery, LINQ to Entities and IQueryable

The return type of a LINQ query is an IQueryable, even a LINQ to Entities query.

Here is a screenshot of a LINQ to Entities query at design time (code is NOT being debugged).

But when the query has been processed, it’s no longer an IQueryable, but an ObjectQuery.

What’s going on here?

At design time, the compiler recognizes that it’s a LINQ query and therefore assumes the return will be an IQueryable.

However LINQ to Entities queries are sent to ObjectServices which return an ObjectQuery, so after it’s processed, it is actually an ObjectQuery.

So, since it’s an ObjectQuery after all, wouldn’t it be nice to leverage ObjectQuery features like MergeOptions on a LINQ to Entities query? You can!

But how? At design time, the query is an IQueryable, not an ObjectQuery and doesn’t have MergeOptions.

No worries. ObjectQuery implements IQueryable.

So you can cast the LINQ to Entities query to an ObjectQuery, set the MergeOption and, as Jeffrey Palermo would say, party on the LINQ to Entities query (though he may not be likely to say that in the context of Entity Framework ;-)).

Using context As New AdventureWorksLTEntitiesDim query = From c In context.Customer Where c.LastName.StartsWith(“S”)Dim objquery = CType(query, ObjectQuery(Of Customer))objquery.MergeOption = MergeOption.OverwriteChangesDim cust = query.ToList.FirstConsole.WriteLine(cust.LastName)cust.LastName = cust.LastName.Trim & “___XYZ”cust = query.ToList.FirstConsole.WriteLine(cust.LastName)End Using

Notice that I’m still performing the operations against the  LINQ query after I cast it to the ObjectQuery.

I could also have done something like

Dim custs = objquery.Execute(MergeOption.OverwriteChanges)

Thanks to Danny for reminding me about the casting! The blog post is intended to lock it into my brain.

  Sign up for my newsletter so you don't miss my conference & Pluralsight course announcements!  

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

This site uses Akismet to reduce spam. Learn how your comment data is processed.