[Entity Framework] Issues with .Include()
Hi all! I have some issues trying to get data from my SQL Db.
Having 3 models (Set, SetContent and Item):
I have 3 pages:
- one to display all Sets
- one to display Content of specific Set
- one to display the specific Item details
The issue that I have is with the third one.
For the Item view page I would like to have a segment showing in what <Set> you can find it.
So my question is how should I form the call in order to get something like Item with SetContent with Set (name and releaseDate):
15 Replies
Ewww,
virtual
Technically, fetching an item from Items
and using .Include(i => i.Sets)
would just work
But I'd recommend opting for .Select()
insteadUnknown User•3y ago
Message Not Public
Sign In & Join Server To View
anything bad with using virtual? 😄
forgot to mentioned that I've tried it since the beginning and even with:
it thrown me into a loop of Item -> Sets -> Item -> Sets=null
It implies you're using lazy loading, which is generally not a great idea
Selecting instead of including should help
What's wrong with lazy loading though? Eager fetching can be pretty bad for performance
Unless you're meaning return anonymous dtos as a better alternative or something?
Not anonymous, yes DTOs
And in most cases you'll get better performance out of fetching, say, a blogpost and its associated tags in one go, rather then querying the database for the blogpost, and then querying it again for each tag
This would be because of lazy loading 😛
When you explicitly load, you don't have those problems
In this case your SetContent should contain a Set (as well as the SetId), which doesn't do anything in the db, just makes it easier to work with on the code side
Then you can do
Context.Items.Include(i => i.Sets).ThenInclude(s => s.Set)
I went with @Angius's rout and just formed a nested Select
I get the intended return without obsolete data
Yep that works too
also tried:
That only queries the database again for little to no reason
So, yeah, good you went with
.Select()
@Angius thanks for helping out (y)
tho should I get rid of Virtual tags in case of Selecting what I want?
ye
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
.Include()
is eager, yes, but virtual
allows for lazy loading to be used
If you're using it, don't
If you aren't, why have virtual
there
One way or another, it's unnecessary