Search code examples
c#entity-framework-corelazy-loadingef-core-6.0

EF Core not loading related entities


My original code:

public static User GetUser(int userID)
{
    _context.Users.Where(x => x.UserId == userID)
                  .FirstOrDefault();
}

Here user.usergovernments is null.

New code:

public static User GetUser(int userID)
{
    using (var _context = new SafetyContext())
    {
        // find lga for this user
        var user_govs = from o in _context.Users
                        join i in _context.UserGovernments                           
                               on o.UserId equals i.UserId
                        where o.UserId == userID
                        select new { o, i };
                            
        var user = _context.Users
                           .Where(x => x.UserId == userID)
                           .FirstOrDefault();

        foreach (var lga in user_govs)
        {
            user.UserGovernments.Add(new UserGovernment { UserId = userID, UserGovernmentId = lga.i.UserGovernmentId, LocalGovId = lga.i.LocalGovId, StateId = lga.i.StateId });
        }

        return user;
     }
 }

This time I get duplicate usergovernment records! One is loaded and the other is the one I added!

Model classes:

public class User
{
    public int UserId { get; set; }
    public string Name { get; set; }

    public string Email { get; set; }

    public UserAccess AccessLevel { get; set; }

    public ICollection<UserGovernment> UserGovernments { get; set; }
}

public class UserGovernment
{
    public int UserGovernmentId { get; set; }
    public int UserId { get; set; }
    public User User { get; set; }
    public int StateId { get; set; }
    public State State { get; set; }
    public int LocalGovId { get; set; }
    public LocalGov LocalGov { get; set; }
}

public class LocalGov
{
    public int LocalGovId { get; set; }
    public string Name { get; set; }        
    public string LgaPid { get; set; }
    public ICollection<UserGovernment> UserGovernments { get; set; }
}

Context:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
     modelBuilder.Entity<UserGovernment>()
                 .HasKey(bc => new {bc.UserGovernmentId});

     modelBuilder.Entity<UserGovernment>()
                 .HasOne(bc => bc.User)
                 .WithMany(b => b.UserGovernments)
                 .HasForeignKey(bc => bc.UserId);
        
     modelBuilder.Entity<UserGovernment>()
                 .HasOne(bc => bc.LocalGov)
                 .WithMany(c => c.UserGovernments)
                 .HasForeignKey(bc => bc.LocalGovId);
}

What am I doing wrong?

LocalGov and User are individual entities while UserGovernments is the many-to-many joining table/entity


Solution

  • Write Query as like bellow. Include method fill your UserGovermnet property automaticaly according to it's matched userId

     _context.Users.Where(x => x.UserId == userID)
        .Include(u=>u.UserGoverments)
                          .FirstOrDefault();