简体   繁体   中英

Entity Framework - Can't seem to load related entities

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.

[Table("User")]
public class User : AuditableEntity
{
  public Group CurrentlySelectedGroup { get; set; }
}

[Table("Group")]
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?

Thanks!

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?

Thanks

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.

try

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class User
{
  [ForeignKey("CurrentlySelectedGroupId")]
  public Group myGroup { get; set; }
}

=================

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM