I have no idea what the keywords are so here is an example of what I want:
return from i in userRepo.GetUsers()
select new SimpleUser{
i.UserId,
i.Name
};
userRepo.GetUsers()
returns type IQueryable<User>
. I'd like to convert this to IQueryable<SimpleUser>
to I can restrict access to certain properties of the User
domain.
How do I do this without hard coding the translation like this? What about tools like automapper or ValueInjecter, how can they do this?
Also, what is this technique called?
Provided that SimpleUser is assigneable to User (User is an interface of baseclass of SimpleUser), you can
var users = simpleUsers.Cast<User>();
optionally with
var users = simpleUsers.Cast<User>().AsQueryable();
And if you're not sure whether all items are actually Users, then you can use OfType<User>
instead of Cast<User>
This question is 9 years old so idk if it existed then but for anyone searching now, using .FirstOrDefault() works if you pick a single user.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With