Loading related objects Vs Query join
Is t开发者_运维问答here a difference/best practice between using the entity framework 4 load
method, as opposed to joining via a foreign key, in order to retrieve child data?
So for example, if I had Order and OrderLines, should I write a query that uses and inner join
say on orderId to retrieve a collection, or should I be doing something like Orders.OrderLines.Load to populate the entity collection?
Thanks
Well it depends if you want to automatically get these associations, or explicitly ask for them.
For example, if you did this:
Order order = ctx.Orders.SingleOrDefault();
OrderLines lines = order.OrderLines; // do you want this null, or populated?
There is a reason why they call it "lazy loading", because your being lazy in that you do not want to explicitly ask for the relationship.
If lazy loading is on (default), that second line will silently do an extra round trip to the db to fetch the order lines.
If you turn lazy loading off, the above line will be null.
And the way to get it is:
Order order = ctx.Orders.Include("OrderLines").SingleOrDefault();
Referred to as "eager loading".
You should not need to explicity perform joins for relationships. If you have the relationships setup correctly in your EDMX (e.g you have a navigational property called "OrderLines" on your "Order" entity), Include will perform a left outer join for you.
You should only need to do explicit joins when the relationship isn't explicitly exposed on the model.
精彩评论