Search code examples
c#entity-frameworklinq-to-entities

ObjectQuery - what is it, how to get to it?


I am reading up on Linq to Entities.

ObjectQuery<T> features prominently in these docs, but I don't quite understand what it is. From what I read, it is an object representing the query. I always thought that when I write a Linq query, I get an IQueryable out of it, so I can a) further compose it or b) enumerate it so it fetches data from the database.

  1. How is ObjectQuery different from an IQueryable?
  2. What is this 'command tree query' mentioned in the article? How is it different from an Expression Tree
  3. Can I get to an ObjectQuery from the IQueryable I get when I write a Linq query?

Links:

https://learn.microsoft.com/en-us/dotnet/api/system.data.objects.objectquery-1?view=netframework-4.8


Solution

  • It's part of System.Data, something separate from LINQ. Since it's converting an SQL-String to objects, it might be useful if for some reasons, you don't want to use LINQ or EF. The newer version in EF is

    context.SqlQuery("Select * from Students").ToList<Student>();
    

    would be the same as

    new ObjectQuery<Student>("Select * from Students", context).
    

    where the context in the latter is an Object Context and a DBContext in the first line. It's all not strongly typed and therefore 'simpler' or Quick & Dirty. Not the recommended way to go.

    Recommended way is having a DbSet < Student> and not handle SQL Strings at all (if avoidable).