Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing eager-loading for a navigation property

I'm using EF Code First and I have a navigation property called Category that I want eager loaded in every call:

public class Product
{
    ...
    public Category Category { get; set; }
}

To do this I have to include it in every call I'll do on Product

var results = from p in db.Products.Include("Category") select p;

Is there a way to have Category property eager loaded, therefore generation a SQL join, in every call without having to include it every time?

thank you

like image 477
Anderson Fortaleza Avatar asked May 10 '11 19:05

Anderson Fortaleza


2 Answers

One simple way would be to define an extension method

static class DbExtensions{
   public IQueryable<Product> ProductsWithCategories(this MyContext db) {
       return db.Products.Include("Category");
   }
}

Which allows you to use

var results = from p in db.ProductsWithCategories() select p;

Not sure if it brings much benefit though...

like image 102
jeroenh Avatar answered Oct 27 '22 18:10

jeroenh


You can use helper method as proposed by @jeroenh but it will not solve situation where you for example want to load order with all ordered products and their categories. EF doesn't have any automatic eager loading configuration as for example available in Linq-to-sql. You must always use Include (either directly or by some helper construction).

like image 31
Ladislav Mrnka Avatar answered Oct 27 '22 18:10

Ladislav Mrnka