DEV Community

Discussion on: One-to-One Relationship with Entity Framework Core

Collapse
 
samselfridge profile image
samselfridge • Edited

Ran through this and couldn't figure out why theAddWeapon returned a character with a proper weapon, but even with the changes to GetCharacterDto, GET /character/{id} and GET /character both have null for weapon.

Turns out it needs to be 'loaded' from the DB in order to be referenced.

Was able to get the GetAll route to return weapon info by adding an Include() to the chain.

More info here:
The Include() call is what does it.

More info here:
docs.microsoft.com/en-us/ef/ef6/qu...

edit - so this is covered a bit in the next section fyi.


 List<Character> dbCharacters = await _context.Characters.Where(u => u.User.Id == GetUserId()).Include(c => c.Weapon).ToListAsync();

Enter fullscreen mode Exit fullscreen mode