Reputation: 6967
I'm not sure how to work around this linq to SQL issue that I have. Properties of a child object in my object graph is not loading as I would expect.
My data access code is encapsulated in a model layer, so the loading of a full object graph needs to be completed before an object is returned.
I use the following code to populate the object graph.
The "Invoice" is the target object here. It has a parent object "Order" and child objects "InvoiceItems".
Everything loads here except for the "OrderItems", which are a direct child of "Order", but are also mapped to "InvoiceItems". They are accessed by reference to the "InvoiceItems" in this context.
This is apparently because the "OrderItems" are two levels away from the "Invoice" object, being accessed via Invoice.InvoiceItems.OrderItem, where as other properties specified in load options map directly to the Invoice.
How do I load objects 2 levels away from the target object?
I hope this makes sense.
using (var dc = new ProjDataContext(Config.ConnectionStringERPDB))
{
if (loadObjectGraph)
{
var loadOptions = new DataLoadOptions();
loadOptions.LoadWith<Invoice>(x => x.InvoiceItem);
loadOptions.LoadWith<Invoice>(x => x.Order);
loadOptions.LoadWith<InvoiceItem>(x => x.OrderItem);
loadOptions.LoadWith<OrderItem>(x => x.Product);
dc.LoadOptions = loadOptions;
}
Invoice invoice = (from c in dc.Invoice
where c.ID == invoiceID
select c).FirstOrDefault();
return invoice;
}
Upvotes: 1
Views: 1095
Reputation: 6967
It seems you can't load more than one level from other information I've since found.
I've added a pretty dirty extra piece of code to populate the properties I need to access.
This probably isn't a great solution - any input welcome!
// Eager loading abover only works for one level
// http://stackoverflow.com/questions/1191331/using-linq-to-sql-how-do-i-eager-load-all-child-and-any-nested-children-results
// http://www.lowendahl.net/showShout.aspx?id=190
if (loadObjectGraph)
{
foreach (InvoiceItem invoiceItem in invoice.InvoiceItem)
{
var ii = invoiceItem;
OrderItem oiList = (from oi in dc.OrderItem
where oi.ID == ii.OrderItemID
select oi).FirstOrDefault();
invoiceItem.OrderItem = oiList;
}
}
Upvotes: 2