How to convert DbSet in Entity framework to ObjectQuery

前端 未结 2 2095
北恋
北恋 2020-12-01 21:51

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 objectC         


        
2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-01 22:01

    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 GetByCustomCriteria(string criteria) where T: class
    {
      var objectContext = ((IObjectContextAdapter)_myModelEntities).ObjectContext;
      //note: _myModelEntities is a DbContext in EF6.
      var objectSet = objectContext.CreateObjectSet();
      return new List(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("it.Id == 1");`
    
    //sample criteria for string field, note the single quotes
    var myClientByName = GetByCustomCriteria("it.Surname == 'Simpson'"); 
    

提交回复
热议问题