How to load the navigation property with EF Core?

entity-framework entity-framework-core

Question

In EF6 we had such option:

context.Set<TEntity>().Attach(entity);
context.Entry(entity).Collection("NavigationProperty").Load();

Since EF Core "goes 100% strictly typed" they have removed Collection function. But what should be used instead?

Added: I mean how to load includes/"navigation collection properties" for ATTACHED entity?

1
3
10/16/2016 10:06:33 AM

Accepted Answer

Explicit Loading was added in Entity Framework Core v1.1. See Microsoft Docs

From the docs:

using (var context = new BloggingContext())
{
    var blog = context.Blogs
    .Single(b => b.BlogId == 1);

    context.Entry(blog)
        .Collection(b => b.Posts)
        .Load();

    context.Entry(blog)
        .Reference(b => b.Owner)
        .Load();
}
6
5/17/2018 10:03:42 AM

Popular Answer

You have 3 methods:

1. Eager loading

e.g.

var blogs = context.Blogs
    .Include(blog => blog.Posts)
    .ToList();

2. Explicit loading

e.g.

var blog = context.Blogs
    .Single(b => b.BlogId == 1);

context.Posts
    .Where(p => p.BlogId == blog.BlogId)
    .Load();

3. Lazy loading (as of EF Core 2.1)

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    => optionsBuilder
        .UseLazyLoadingProxies()
        .UseSqlServer(myConnectionString);

You can read more about it here : Loading Related Data

Update :

You can use TrackGraph API for that use case.Here is the link : graph behavior of Add/Attach

Another link : DbSet.Add/Attach and graph behavior



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow