Wednesday, 19 November 2008

Dealing with joins that may produce null

This particular example was used to help resolve an issue. I wanted to list invoices and the customerid. Unfortunately some of the data was bad and the invoices didn't have parent records. In this particular situation fixing the data integrity issue wasn't an option. Also there are lots of times you may need to do this regardless of data integrity

'Create a customer object to represent the null customer

Dim null_customer As New svc.Customer
null_customer.CustomerID = -1


'In this case we are selecting into a named type

Dim Search_Flattened As IQueryable(Of Customer) = _
(From t In SearchResult _
Select New Advice.JobAbout _
With {.CustomerID = t.Customers.DefaultIfEmpty(null_customer).FirstOrDefault.CustomerID, _
.DateTimeModified = t.DateTimeModified, _
.AddedBy = t.AddedBy, .InvoiceID = t.InvoiceID})

Now the .CustomerID is -1 for the invoice if there is no parent record.

No comments: