✅ EF - How to extract LINQ Select into a method does not work
I am trying to only include only the needed columns from a table with EF, by using
Select
.
The following class is given:
Having a DbSet<Animal> Animals
, I can do the following to select only the Id:
This works perfectly, but If I extract the object creation into a method, then the generated SQL query will still select all columns.
I am using TPC Inheritance and need to repeat some Select on individual Tables, that's why I am trying to extract the logic from Select
. That way I would avoid repetition (DRY)
I even tried a static class for creating the object, but it did not work.
Given the outcome, I am left with the impression that it is not possible what I am trying to do, but it would be great if someone proved me wrong.9 Replies
No, its not possible as such due to how EF needs to look at the expression generated by the select
There are ways to work around it, but its.. not pretty
create an extension method to operate on
IQueryable<Animal>
That's what I did, but like this:
These are my actual classes, but as you can see there are multiple Selects which are repeated. That's why I tried to extract the logic
i dont really understand the complexity of that
at a crude level you can do:
i also advise you dont project into your actual entity type, and use DTOs instead
Thank you guys
I do that on Controller level, Business, Repo layer works with entity types
I'm not sure I understand. you're still projecting. You're half hydrating your entity type and abusing it to end up in an illegal state.
oh, do you refer to the explicit conversion, like
(Link)MapToUnbrandedLink(l)
?I'm referring to the original question:
_dbContext.Animals.Select(a => new Animal {Id = a.Id})I don't know what either of these two methods do
My bad for not sticking with the initial example. But I understand now what you meant
Alright, I ended up with a way cleaner code, thanks!