Entity Framework Core null object one-to-one

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

Question

Null object in Entity Framework Core. I relate to you as a single entity.

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; }
}

I go back to my player controller.

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

But here is my json.

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

Is this intended to have a null rating?

When I call, FTI

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

I get the proper ranking.

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

Popular Answer

Is rating supposed to be null here?

Yes, but you've enabled sluggish loading, which EF Core doesn't do by default.

You should study the whole Related Data Loaded EF Core documentation article since it outlines the three supported loading patterns, eager, explicit, and lazy. You must utilise one of them to get your navigation property loaded since there is no implicit loading.

For instance, the explicit loading:

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

with eager loadingInclude / ThenInclude is a more sensible option, but it requires the usage of not compatible withFind / FindAsync, thusFirstOrDefault / SingleOrDefault (Or yourAsync equivalents) in this way:

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