How to convert DbSet in Entity framework to ObjectQuery

空扰寡人 提交于 2019-11-27 09:15:28
inspiringmyself

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.
Spyder

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'"); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!