Home > Back-end >  Entity Framework relationships not loading
Entity Framework relationships not loading

Time:07-29

I generated my DbContext and entity types using the Scaffold-DbContext command in powershell.

I can successfully retrieve records from the database however, the relationships always seem to be null.

Asset.cs

class Asset
{
    [ForeignKey("CategoryId")]
    public virtual AssetCategory Category { get; set; } = null!;
}

The relationship configuration appears to be OK in the DbContext file that was automatically generated.

entity.HasOne(d => d.Category)
    .WithMany(p => p.Assets)
    .HasForeignKey(d => d.CategoryId)
    .OnDelete(DeleteBehavior.ClientSetNull)
    .HasConstraintName("FK_Asset_AssetCategory");

What I do note is that the Constraints folder within the database for the Asset table is empty?

Example usage

// basic properties of asset are correctly hydrated here, just not relationships
var asset = await _dbContext.Assets.FindAsync(id);

// category is always null
var category = asset.Category;

This happens with all the relationships defined on the entity model and I don't understand why?

CodePudding user response:

Thanks to the comments from DavidG pointing out I needed to use the Include method to load the relationship(s) as they are not automatically lazy loaded.

var asset = _dbContext.Assets
                      .Where(a => a.id == id)
                      .Include(a => a.Category)
                      .FirstOrDefaultAsync();
  • Related