JustinT
JustinT

Reputation: 692

Map Func<Type1, bool> to Func<Type2, bool>

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>?

Upvotes: 2

Views: 500

Answers (1)

Jeff Mercado
Jeff Mercado

Reputation: 134601

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 the Where() filter since the collection is of the correct type.

var users = entityFramework.Users
                           .Select(user => (DTO.User)user) //perform the conversion
                           .Where(whereClause);

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.

Func<Entities.User, bool> newWhereClause = user => whereClause((DTO.User)user); //convert here

Upvotes: 1

Related Questions