Search code examples
asp.net-mvcautomappervalueinjecter

ValueInjecter with IQueryable<T>


I need to map IQueryable<User> to IQueryable<SimpleUser> with ValueInjecter.

Is this possible?

I tried:

return userRepo.GetUsers()
               .Select(o => new SimpleUser().InjectFrom(o))
               .Cast<SimpleUser>();

But this cannot be translated to a stored expression...well, the method InjectFrom.

Can automapper do this?

I want something similar to this:

return from i in userRepo.GetUsers()
      select new SimpleUser{
            i.UserId,
            i.Name
      };

but with using some kind of mapper tool.


Solution

  • Convert the collection to objects before doing the select and it should work. Updated using PredicateBuilder to show filtering and paging and Dynamic LINQ for sorting.

    var predicate = new PredicateBuilder<User>.True();
    if (!string.IsNullOrEmpty( typeFilter ))
    {
        predicate = predicate.And( u => u.Type == typeFilter );
    }
    if (!string.IsNullOrEmpty( nameFilter ))
    {
        predicate = predicate.And( u => u.Name.StartsWith( nameFilter ));
    }
    
    // assumes sortColumn matches one of your user properties and
    // sortDirection is either "ASC" or "DESC"
    string sortOrder = string.Format( "{0} {1}", sortColumn, sortDirection ); 
    
    return userRepo.GetUsers()
                   .Where( predicate )
                   .OrderBy( sortOrder )
                   .Skip( (page-1) * usersPerPage )
                   .Take( usersPerPage )
                   .ToList()  // force the query and make these objects
                   .Select(o => new SimpleUser().InjectFrom(o))
                   .Cast<SimpleUser>();