public class MyDbContext: DbContext { } public class Product { public long Id {get; set;} public long CategoryId {get; set;} [ForeignKey("CategoryId")] public virtual Category Category {get; set;} } public class Category { public long Id {get; set;} public string Name {get; set;} } List<Product> GetProducts() { var context = new MyDbContext(); var products = context.Set<Product>().ToList(); var categories = context.Set<Category>().ToList(); foreach(var product = in products) { product.Category = categories.First(c => c.Id == product.CategoryId); } return products; } Here I want to retrieve all products with associated categories with best performance. I first tried with lazy loading, but it results in many database queries. Then I use eager loading, but the query scripts generated are not so efficient especially for complex query. So I used the following way:
get all Products,
get all Categories and
set the navigation property "Category" of a product manually from the fetched categories
My questions are:
-Will EF still lazy load the navigation property "Category" even after I set it manually?
-Is there any better solution to eager loading for complex query?