Reputation: 11350
I'm using Entity Framework 4.3 with a unit-ofwork/repository pattern. In this instance, the unit of work is a request.
The unit of work also explicitly sets lazy loading to true.
I am however a little confused about when things are lazy loaded in this scenario, and some advice would be appreciated.
var context = Local.Items.Uow.Context; // the context
var r = new ReadRepo<Deal>(context); // the repository
var deals = r.Find(); // IQueryable<Deal>
Rpt_BookmarkedDeals.DataSource = deals.ToList();
Rpt_BookmarkedDeals.DataBind();
The repository Deals, has a navigation property of 'Store'. The requirement to load Store is only known when the repeater is databound. I'm guessing this is where the nav property is loaded but I'm not sure.
Is this the best way of doing this or should I explicitly add Store as an Include() when I get Deals?
Upvotes: 3
Views: 1102
Reputation:
The requirement to load Store is only known when the repeater is databound. I'm guessing this is where the nav property is loaded but I'm not sure.
Yes, a lazily loaded navigation property gets loaded when the property is referenced, and binding to that property references it.
Is this the best way of doing this or should I explicitly add Store as an Include() when I get Deals?
There is no single best way.
If your deals link to 10 different stores, then lazily loading deal.Store
will result in 10 separate queries that get sent to the database, in addition to the one query that gets the deals. If you use deals.Include("Store")
, one query will retrieve both the deals and the stores in one go, but the data for each store is repeated for each deal. Which one performs better depends.
If you use lazy loading, you may get inconsistencies if a store and its deals gets deleted after the deals are loaded, but before the stores are. This can be avoided by using a transaction, but in that case, the transaction will have to last until the stores are loaded.
You need to weigh the advantages and disadvantages of the different methods to determine which one is best for your situation.
Upvotes: 4