I’m using Entity Framework behind a set of repositories. The repositories use DTOs instead of the entity objects generated by the Entity Framework. I’m using AutoMapper to convert them back and forth.
I’m having trouble figuring out how to do the following:
Method definition:
public IEnumerable<DTO.User> Get(Func<DTO.User, bool> whereClause)
Example:
var users = userRepository.Get(usersWhere => usersWhere.PostCount > someNumber);
And I’d like to be able to pass that Func<T, bool> on to the Entity Framework like so:
var users = entityFramework.Users.Where(whereClause);
Obviously, that won’t build, because the .Where() method is expecting an Entities.User, not a DTO.User.
Is there a way to convert a Func<DTO.User, bool> into a Func<Entities.User, bool>?
You can use the
Select()method to perform the conversion either through a cast, a call to a constructor or other. You could then use your function in theWhere()filter since the collection is of the correct type.An alternative approach would be to create a new function with the correct types to perform the conversion from within. Then you may use the new where clause.