Entity Framework - Include two levels deep selected properties

Viewed 36

The entity framework provides navigation elements for foreign keys. If you use lazy loading, the navigation elements have NULL values otherwise .Include loads the entire object

ObjectA = await _context.ObjectA.Include(b => b.ObjectBNavigation)

What if the navigation element is large and you need only Name property? Then you need to additionaly use .Select and create a new object that contains the properties you need

ObjectA = await _context.ObjectA
.Include(b => b.ObjectB)
.Select(b => new ObjectA() 
{
    Name = b.Name,
    ObjectBNavigation = new ObjectB() { Name = b.ObjectBNavigation.Name },
})
.ToListAsync();

Now you can display element Name insted of element Index

@if(item.ObjectA != null)
@Html.DisplayFor(modelItem => item.ObjectBNavigation.Name)

And the Index page loads in an instant. I hope this will be helpfull for other ASP.NET newbies like me.

public partial class ObjectA
{
    public int Id { get; set; }
    public string Name { get; set; } = null!;
    public int? ObjectBId { get; set; }

    public virtual ObjectB? ObjectBNavigation { get; set; }
}

public partial class ObjectB
{
    public int Id { get; set; }
    public string Name { get; set; } = null!;
}
0 Answers
Related