One to Many relationships in EF Core 3.0 returning Null

c# entity-framework-core


I want to create a one to many relationships in EF Core 3.0 where Users can have multiple games but when I pull up the route for a user in postman the Games field is returning null. How do this properly? Here's my model.

using System;
using System.Collections.Generic;

namespace Domain
    public class User
       public int UserId { get; set; }
       public string UserName { get; set; }
       public string Email { get; set; }
       public List<Game> Games {get; set;}

   public class Game
       public int GameId {get; set;}
       public string GameName { get; set; }
       public int UserId {get; set;}
       public User User {get; set;}
2/7/2020 4:24:45 AM

Accepted Answer

The reason is explained in the Loading Related Data section of the EF Core documentation.

The first behavior is because EF Core currently does not support lazy loading, so normally you'll get null for navigation properties until you specifically load them via eager or explicit loading. However, the Eager loading section contains the following:

Entity Framework Core will automatically fix-up navigation properties to any other entities that were previously loaded into the context instance. So even if you don't explicitly include the data for a navigation property, the property may still be populated if some or all of the related entities were previously loaded.

which explains why the navigation property is not null in the second case.

Now, I'm not sure which of the two behaviors do you want to fix, so will try to address both.

The first behavior can be "fixed" by using one of the currently available methods for loading related data, for instance eager loading:

var mutants = db.Mutants.Include(m => m.OriginalCode).ToList();

The second behavior is "by design" and cannot be controlled. If you want to avoid it, make sure to use fresh new DbContext instance just for executing a single query to retry the data needed.

Update: Starting with v2.1, EF Core supports Lazy Loading. However it's not enabled by default, so in order to utilize it one should mark all navigation properties virtual, install Microsoft.EntityFrameworkCore.Proxies and enable it via UseLazyLoadingProxies call, or utilize Lazy-loading without proxies - both explained with examples in the EF Core documentation.

7/9/2018 6:02:40 PM

Related Questions


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