Explicitly load all navigation properties

c# entity-framework-core

Question

EF Core recently added explicitly load the navigation properties of an object;

using (var db = new BloggingContext()) {
    var blog = db.Blogs.Find(1);

    db.Entry(blog).Collection(b => b.Posts).Load();
    db.Entry(blog).Reference(b => b.Author).Load();
}

https://blogs.msdn.microsoft.com/dotnet/2016/11/16/announcing-entity-framework-core-1-1/

This is obviously verbose, and I don't wish to do these checks every time. Is there any extension methods or complementary NuGet packages available to get around these shortcomings?

I realise this is a common question, but not for EF Core.

EntityFramework Eager Load all Navigation Properties

1
0
5/23/2017 11:52:59 AM

Accepted Answer

As mentioned in comments I'm fairly confident (though my usage of EF Core is limited) that this can't be done automatically through standard mapping of navigation properties. Also using .Load is less efficient (and much longer) than using .Include as you'll be running multiple queries just like using the lazy-loading navigation property itself.

There are 2 ways I can think of to approach the problem of not wishing to do the checks every time as per your question. The first would work for loading your Blog entity specifically, and the second that you could reuse across others but still requires changes to your loading.

1; Extension Method to load all related entities, something like this:

public static IQueryable<Blog> EagerWhere(this DbSet<Blogs> dbset, Expression<Func<Blog, bool>> expr) {
    return dbset
        .Include(m => m.Posts)
        .Include(m => m.Author)
        .Where(expr);
}

// .. usage

db.Blogs.EagerWhere(m => m.Id == 1);

(Note that I wrote this as EagerWhere so you have more control over the query so it's more reusable rather than a simple Find replacement)

2; Write a custom attribute, and write a method used similar to the above that performs the same action as .Find(..) but uses Reflection to find the properties with your custom attribute, and passes them into .Include(..) recursively.

I won't write an example for that as I'm not sure it's worth the effort due to the (normally) limited amount of entities created.

2
11/24/2016 11:23:52 AM


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