C
C#9mo ago
WarningShoot

❔ Ef core relations

Hey, im working on a simple project and im getting so much confused about how efcore works. I have two simple classes, where one have List of second one, and when i want to acces this list its always null.
No description
No description
No description
No description
14 Replies
WarningShoot
WarningShoot9mo ago
it works when i do something like this
WarningShoot
WarningShoot9mo ago
No description
WarningShoot
WarningShoot9mo ago
but i think its really bad if i need to do this
Angius
Angius9mo ago
Delete that .ToList() And, yes, generally speaking using a .Select() is preferable to .Include()
WarningShoot
WarningShoot9mo ago
i think u didnt understand me.
i would like to do something like this
i would like to do something like this
cs var requestedQuestionnaire = _context.Questionnaires .FirstOrDefault(x => x.Id == Id); foreach(var option in requestedQuestionnaire.Options) { // do some stuff } ``` i cant do that because options is null
Angius
Angius9mo ago
You want just the options? If you want it all, you can still do
var requestedQuestionnaire = _context.Questionnaires
.Include(x => x.Options)
.FirstOrDefault(x => x.Id == Id);
var requestedQuestionnaire = _context.Questionnaires
.Include(x => x.Options)
.FirstOrDefault(x => x.Id == Id);
Bonus points if you make it async
WarningShoot
WarningShoot9mo ago
yea i get it but i done it before and i didnt have to use Include()
Angius
Angius9mo ago
Then you probably had lazy loading turned on Which you shouldn't do
WarningShoot
WarningShoot9mo ago
hmm maybe idk
Angius
Angius9mo ago
Lazy loading queries the database each time a navigation property is accessed Eager loading with .Include() or better yet, .Select(), only queries the database once and gets all the data
WarningShoot
WarningShoot9mo ago
okay thanks ❤️ could you tell me how to do it with select?
Angius
Angius9mo ago
You would create a new class, or multiple classes, that contain only the properties you need And select into those
// User has id, name, surname, date of birth
// Pet has id, name, breed
var user = await _context.Users
.Where(u => u.Id == id)
.Select(u => new UserDto { // class with only select properties
Name = u.Name,
PetNames = u.Pets.Select(p => p.Name)
})
.FirstOrDefaultAsync();
// result
// UserDto {
// Name = "Bob",
// PetNames = [ "Rex", "Caesar", "Fish McFishFace" ]
// }
// User has id, name, surname, date of birth
// Pet has id, name, breed
var user = await _context.Users
.Where(u => u.Id == id)
.Select(u => new UserDto { // class with only select properties
Name = u.Name,
PetNames = u.Pets.Select(p => p.Name)
})
.FirstOrDefaultAsync();
// result
// UserDto {
// Name = "Bob",
// PetNames = [ "Rex", "Caesar", "Fish McFishFace" ]
// }
WarningShoot
WarningShoot9mo ago
Big thanks for you ❤️
Accord
Accord9mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.