views:

404

answers:

2

I have entity type Order which has a reference to an entity type Customer. There's a function import that return a list of Order based on a criteria. This list of Orders in displayed in a Datagrid which shows

Order.Date | Order.Customer.Name | Order.Total

For Customer.Name to show up I need to load the CustomerReference in each Order in the list, but each call to Order.CustomerReference.Load() whould make a round trip to the SQL Server and make the whole process very inefficient. The question is, if I have a single query that retrieves all Customer data for all Orders in the list, how do I manually populate the CustomerReference in each Order?

Basically I need to do .Include("Customer") with a function import.

Thanks

+2  A: 

If you execute a query that brings back all the related customers in one go, there is no need to manually populate each CustomerReference. This is because something called Relationship Fixup does this for you automatically.

i.e. if you do this:

Order o = ctx.Orders.First(o => o.Customer.ID == 1);
// at this point o.Customer == null

Customer c = ctx.Customers.First(c => c.ID == 1);
// at this point o.Customer == c

Relationship Fixup means that after the customer enters the context all related object will automatically now point to it...

I.e. this is a lot easier than you think!

Hope this helps

Alex

Alex James
A: 

Thanks Alex, I tried that. It works as you said but apparently it doesn't work on derived entity type. Order Entity Type is an abstract base class which has a derived class Sale.

Order o1 = ctx.Orders.First(o => o.Customer.ID == 1); 
Sale s1 = ctx.GetSaleByCustomerID_FunctionImport(2).First(); 

Customer c = ctx.Customers.First(c => c.ID == 1); 
Customer c2 = ctx.Customers.First(c => c.ID == 2);
//At this point o.Customer == c but s1.Customer is still null

And I can't set the function import return type as Order because it's abstract and not allowed as a return type.

What am I missing here?

Update: I found out there's a difference between o1 and s1 before the customers are loaded o1.CustomerReference.IsLoaded is False o1.CustomerReference.EntityKey is ID = 2

s1.CustomerReference.IsLoaded is False s1.CustomerReference.EntityKey is null

But calling s1.CustomerReference.Load() would correctly load the Customer data. I double checked my GetSaleByCustomerID Function Import (simply "SELECT * FROM Customers WHERE ID = 2"), it does return the CustomerID field required by the reference.

Olonarp