How to convert DbSet in Entity framework to ObjectQuery

inspiringmyself picture inspiringmyself · Jun 28, 2012 · Viewed 17.3k times · Source

I am using CodeFirst approach and struck with an issue where I need to convert DbSet to ObjectQuery. This is what I did for conversion.

ObjectContext objectContext = ((IObjectContextAdapter)db).ObjectContext;
ObjectSet<Request> objectSet = objectContext.CreateObjectSet<Request>();

where db is the context inheriting from DbContext and Request is class.

So, when I try to call the method that expects ObjectQuery as ObjectQueryMethod(objectSet), it throws the following error.

"Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Data.Entity.DbSet<>' and 'System.Data.Objects.ObjectQuery<>'"

Any help is greatly appreciated!

Answer

inspiringmyself picture inspiringmyself · Jun 29, 2012

I found the answer. Of course, it is possible to convert DbSet in Entity framework to ObjectQuery using the below lines of code.

ObjectContext objectContext = ((IObjectContextAdapter)db).ObjectContext;  
ObjectSet<Request> objectSet = objectContext.CreateObjectSet<Request>("Requests");

where,

  • db - Context class inherting from DbContext.
  • Requests - DbSet<Request> defined in Context class.
  • objectSet - Can now be passed as ObjectQuery.