Roman Pokrovskij
Roman Pokrovskij

Reputation: 9776

How to load the navigation property with EF Core?

In EF6 we could do the following:

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

Since EF Core is going "100% strictly typed", they have removed the Collection function. What should we use instead?

How do I load navigation properties for an ATTACHED entity? That is, do I have a way to invoke something like .Include() and .ThenInclude(), on an entity I have already retrieved?

Upvotes: 15

Views: 22253

Answers (3)

Sampath
Sampath

Reputation: 65870

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

Upvotes: 22

Mog0
Mog0

Reputation: 2087

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();
}

Upvotes: 24

Pankaj Rawat
Pankaj Rawat

Reputation: 4573

See below Code,
I'm inserting data in UserRef table as well another table which we have many 2 many relationships.

public void AddUser(User user, IEnumerable<UserSecurityQuestion> securityQuestion, string password)
    {
        var userModel = _mapper.Map<User, UserRef>(user);
        userModel.CreateTime = DateTime.Now;

        userModel.UserNewsLetterMaps.ToList().ForEach(u => this._context.UserNewsLetterMaps.Add(u));            
        this._context.RoleRefs.Attach(new RoleRef() { RoleId = (int)user.UserRole, UserRefs = new List<UserRef> { userModel } });
        userModel.ResidenceStatusRefs.ToList().ForEach(u => this._context.ResidenceStatusRefs.Attach(u));
        this._context.UserRefs.Add(userModel);
        this.Save();
    }

Upvotes: 1

Related Questions