开发者

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, bo开发者_C百科ol> 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 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜