views:

50

answers:

1

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

+1  A: 

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
Jeff M
I believe the second way was what you were after but the first I think is the most sensible. I'm not too familiar with LINQ-to-Entities so I don't know if either approach works as is and may need tweaking (if it's anything like LINQ-to-SQL).
Jeff M
I used the second approach. From my shaky understanding of how Entity Framework pulls records, the first method would pull all of the User rows from the database before casting them. Perhaps somebody who knows more could confirm that.
JustinT