Entity Framework - Can't seem to load related entities

c# entity-framework entity-framework-core


I'm a bit of an EF newb and I'm using .net core and I just can't seem to load the related entities of an entity unless I do a full-fledged "from..in..join" linq statement.

My entities have Guid primary keys and I'm using SQL Server as a DB.

Let's look at one entity that I'm having trouble with.

public class User : AuditableEntity
  public Group CurrentlySelectedGroup { get; set; }

public class Group : AuditableEntity
  public string Name { get; set; }

A user can pick one group as their "selected" group. I ran the migration statement and sure enough it created exactly what I wanted on the DB - a brand new column called CurrentlySelectedGroupId that was a FK to the Group table's PK column.

So this looks great.

I then ran some code that added a valid Guid for a valid group into the table.

Now when I execute this line of code:

 var user = _dbContext.Users.Where(u => u.Id == userId).FirstOrDefault();

It returns my user perfectly, but all the related entities are null. I've even tried things like .Include(), including 'virtual', but no luck.

Any idea what I'm doing wrong?


9/20/2018 4:54:25 AM

Accepted Answer

Lazy loading is not enabled, this feature was included in EF Core 2.1. In your case Explicit Loading is happening so you need to explicitly load the related entities. So If you are using EF Core 2.1, you can just enable the Lazy Loading and use related entities without explicitly adding them.

9/20/2018 4:33:41 AM

Popular Answer

After much trial and error, it seems the following works:

  var user = _dbContext.Users.Single(u => u.Id == userId);
  _dbContext.Entry(user).Reference(u => u.CurrentlySelectedGroup).Load();

Any ideas why this would work yet not anything else?


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