Entity Framework Core null object one-to-one

c# entity-framework-6 entity-framework-core model null

Question

Entity Framework Core null object. I have a one-to-one entity relationship.

public class Player
{
    public int Id { get; set; }

    public int? RatingId { get; set; }

    public Rating Rating { get; set; }
}

public class Rating
{
    public double Mean { get; set; }
}

In my player controller I return

var player = await _context.Player.FindAsync(id);

However this is my json

{
    "id": 3010,
    "ratingId": 2009,
    "rating": null,
    "displayName": "Conor",
    "partialPlayPercentage": 0.5,
    "partialUpdatePercentage": 1
}

Is rating supposed to be null here?

FTI When I call

var rating = await _context.Rating.FindAsync(2009);

I get the correct rating

1
1
9/14/2018 3:45:50 PM

Popular Answer

Is rating supposed to be null here?

Yes, except you have Lazy loading enabled, which in EF Core is not by default.

I would suggest you reading the whole Loading Related Data EF Core documentation topic which explains the 3 supported patterns - Eager, Explicit and Lazy loading. Note that there is no implicit loading, so you have to use one of those in order to get your navigation property loaded.

For instance, the explicit loading:

var player = await _context.Player.FindAsync(id);
if (player != null)
    _context.Entry(player).Reference(e => e.Rating).Load();

The eager loading with Include / ThenInclude is more natural choice, but it can't be used with Find / FindAsync, so you need to use FirstOrDefault / SingleOrDefault (or their Async counterparts) like this:

var player = await _context.Player
    .Include(e => e.Rating)
    .FirstOrDefaultAsync(e => e.Id == id);
2
9/14/2018 5:19:59 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow