Is it possible to map IQueryable to IQuery

2019-06-22 05:16发布

问题:

This is a question for Automapper professionals. I have tried to do query mapping for several days already - and no luck. Seems like Automapper is not intended to be used the way I want to use it. But maybe I am wrong. So here is the question...

I have such classes:

  • CatDto (Name, Age, Toys (collection of ToyDto objects))
  • ToyDto (CatName, ToyName, Cat (parent CatDto object))
  • Cat (comes from Entity Framework, has properties similar to those in CatDto)
  • Toy (comes from Entity Framework, has properties similar to those in ToyDto)

I want to write a generic read function in my data access layer, something like this:

IEnumerable<CatDto> Read(IQueryable<CatDto> query) {
    // here "query" is converted 
    // to Entity Framework query by means of AutoMapper,
    // EF query gets executed,
    // I convert EF entities (Cat) back to CatDto - this is not essential
    // result is returned
}

I will call this function in different manners. Example:

var q = new ObjectModel.Collection(Of CatDto)).AsQueryable();
q = q.Where(c => c.Toys.Count() > 1);
var someResultVar = Read(q);

So far any attempts to implement such behavior have failed. I wonder if Automapper is a helper here or am I going completely wrong way?

回答1:

I believe the functionality you want is in UseAsDataSource

You can't map IQueryable, but you shouldn't need to with UseAsDataSource Example

IQueryable<CatDto> someResultVar  = new ObjectModel.Collection(Of CatDto)).AsQueryable().UseAsDataSource().For(Of OrderLineDTO).Where(c => c.Toys.Count() > 1);

When you enumerate it will convert Lambda from CatDto to CatEf and call ProjectTo<CatDto> and return CatDto objects