I first discovered linq to crm and early bound classes way back in 2011. The sky (well the office ceiling) literally dawned on me when i discovered it. Along the way, i’ve learned its merits, pitfalls, nuances. Until this day, it’s still the query of choice on the server side, over query expression and fetchxml. But this post is not about pros/cons analysis. There are plenty out there. There’s a saying – “you learn something new every day” and here’s what i’ve learned today. It’s about join queries and returned objects.
In early bound generated classes, crmsvcutil generates two things in regards to N:1 relationship: an entityreference field and a class variable of type of the N:1. I’ve used the latter in lazy loading features before (when i’m feeling lazy coding) in portal development (because it’s only available in microsoft.xrm.client and not microsoft.xrm.sdk.client, which is available in plugin) Today, i found that i can actually populate it with selected fields in a join select query:
var invoicedata = (from inv in ctx.InvoiceSet
join invdetail in ctx.InvoiceDetailSet on inv.InvoiceId equals invdetail.InvoiceId.Id
join p in ctx.ProductSet on invdetail.ProductId.Id equals p.ProductId
where inv.InvoiceId == invid
select new InvoiceDetail()
{
invoice_details = new Invoice()
{
InvoiceId = inv.InvoiceId,
Name = inv.Name,
InvoiceNumber = inv.InvoiceNumber
},
product_invoice_details = p
}).ToList();
So as you can see, at the end of the query, in addition to the root level invoice detail data, the select actually instantiates the N:1 invoice, and product inside it. pretty sweet huh?