Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert DbSet in Entity framework to ObjectQuery

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!

like image 434
inspiringmyself Avatar asked Jun 28 '12 20:06

inspiringmyself


People also ask

Is DbSet part of DbContext?

The DbSet class represents an entity set that can be used for create, read, update, and delete operations. The context class (derived from DbContext ) must include the DbSet type properties for the entities which map to database tables and views. Adds the given entity to the context with the Added state.

What is DbSet in Entity Framework?

A DbSet represents the collection of all entities in the context, or that can be queried from the database, of a given type. DbSet objects are created from a DbContext using the DbContext. Set method.

What is DbSet and entity set?

In Entity Framework Core, the DbSet represents the set of entities. In a database, a group of similar entities is called an Entity Set. The DbSet enables the user to perform various operations like add, remove, update, etc. on the entity set.


1 Answers

Thanks for the correct answer 'inspiringmyself'; this is just to elaborate on your answer. I managed to do this with a generic type, so just to share it:

private List<T> GetByCustomCriteria<T>(string criteria) where T: class
{
  var objectContext = ((IObjectContextAdapter)_myModelEntities).ObjectContext;
  //note: _myModelEntities is a DbContext in EF6.
  var objectSet = objectContext.CreateObjectSet<T>();
  return new List<T>(objectSet.Where(criteria));
 }

And I thought the above post could do with an example of what criteria to send so here's an example:

 //sample criteria for int field:
 var myClientById = GetByCustomCriteria<Client>("it.Id == 1");`

//sample criteria for string field, note the single quotes
var myClientByName = GetByCustomCriteria<Client>("it.Surname == 'Simpson'"); 
like image 66
Spyder Avatar answered Sep 29 '22 23:09

Spyder