Convert IQueryable <T> object to another object?

I have no idea what keywords are, here is an example of what I want:

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

userRepo.GetUsers() returns the type IQueryable<User> . I would like to convert this to an IQueryable<SimpleUser> so that I can restrict access to certain properties of the User domain.

How can I do this without hard coding translation? What about tools like automapper or ValueInjecter, how can they do this?

Also, what is this technique called?

+7
source share
3 answers

You must hard convert the translation or first convert it to IEnumerable . IQueryable is an expression tree translated to some execution in the provider used - in your case, I think it will be an Entity infrastructure. You cannot use any kind of automatic matching in such a query because it will be translated into SQL that your .net or AutoMapper methods will not understand. Custom type forecasts are part of the request and must be hard-coded. You can create your own extension method to IQueryable and reuse it where you need it:

 public static IQueryabe<SimpleUser> ProjectToSimpleUser(this IQueryable<User> query) { return query.Select(u => new SimpleUser { // Here map your fields }); } 

Now you can use:

 return repo.GetUsers().ProjectToSimpleUser(); 

In the case of an Entity infrastructure, SimpleUser should not be a mapped object.

+9
source

AutoMapper is the tool you need; it works through reflection, and unless you tell it to do otherwise, it will display properties with the same name directly.

Automatic matching is a method.

+4
source

Provided that SimpleUser is assigned to the user (The user is the interface of the SimpleUser base class), you can

  var users = simpleUsers.Cast<User>(); 

optionally with

  var users = simpleUsers.Cast<User>().AsQueryable(); 

And if you're not sure if all the elements are actually users, you can use OfType<User> instead of Cast<User>

+3
source

All Articles