Let's say we have four entities in data model: Categories, Books, Authors and BookPages. Also assume Categories-Books, Books-Authors and Books-BookPages relationships are one-to-many.
If a category entity instance is retrieved from database - including "Books", "Books.BookPages" and "Books.Authors" - this will become a serious performance issue. Moreover, not including them will result in "Object reference is not set to an instance of an object" exception.
What is the best practice for using multiple Include method calls?
- Write a single method GetCategoryById and include all items inside (performance issue)
- Write a single method GetCategoryById and send a list of relationships to include (maybe, but still seems not elegant enough)
- Write methods like GetCategoryByIdWithBooks, GetCategoryByIdWithBooksAndBooksPages and GetCategoryByIdWithBooksAndAuthors (not practical)
EDIT: By second option I meant something like this:
public static Category GetCategoryById(ModelEntities db, int categoryId, params string[] includeFields)
{
var categories = db.Categories;
foreach (string includeField in includeFields)
{
categories = categories.Include(includeField);
}
return categories.SingleOrDefault(i => i.CategoryId == categoryId);
}
When calling we need a code like this:
Category theCategory1 = CategoryHelper.GetCategoryById(db, 5, "Books");
Category theCategory2 = CategoryHelper.GetCategoryById(db, 5, "Books", "Books.Pages");
Category theCategory3 = CategoryHelper.GetCategoryById(db, 5, "Books", "Books.Authors");
Category theCategory4 = CategoryHelper.GetCategoryById(db, 5, "Books", "Books.Pages", "Books.Authors");
Are there any distinct disadvantages of this approach?
Include
is for eager loading rather than lazy loading. I don't know how that happened but at the moment I am not having this issue. Maybe EF update solved it, I am not sure. Anyway, thanks for clearing things up. I will now go over other answers. – Galvanoscope