LTR
LTR

Reputation: 1352

EF Lazy-Loading: Add item to navigation property without loading it

Suppose the following data model:

class Garden
{
    int ID;
    ICollection<Tree> Trees;
    string Address;
}
class Tree
{
    public int ID;
    public float Size;
}

Let's plant some trees:

var gardens = dbContext.Gardens.Take(10).ToList();
foreach (var g in gardens)
    g.Trees.Add(new Tree());

But now, each reference to g.Trees triggers a database query, because of lazy-loading. I could do .Include(garden => garden.Trees) when fetching the gardens, but then I'm transferring all the existing trees.

I could create a GardenID column in Tree, and then just add the Tree to my DbContext without touching the navigation property. But now I need to pass my DbContext around.

How can I add the tree to the garden without triggering a lazy-load of the navigation property, and without transferring unneeded data?

Upvotes: 3

Views: 705

Answers (1)

OrdinaryOrange
OrdinaryOrange

Reputation: 2712

If you are using DB first then you only option is to turn off the lazy loading for the whole context. ctx.Configuration.LazyLoadingEnabled = false

If using Code First then make sure mark your ICollection<Tree> Trees is not virtual which then disables lazy loading just for this collection.

Upvotes: 1

Related Questions