So one of the great things about LINQ is that whenever you have a table in
your datacontext that has a foreign key on it, the foreign table's object is
accessable as a property on the current table's object. So if as an arbitrary,
Northwind-ish example, you have an Order table in the database that has a
CustomerID in it, and you retrieve an Order object from LINQ, you don't just
have the CustomerID accessable from order.CustomerID, but you can access the
whole Customer object by just saying order.Customer! That gives you access to
all of the fields in the Customer table as well, so you could say
order.Customer.FirstName and get the first name of the ordering customer right
from the order object itself. Fyi, this also goes the other way; you should be
able to say customer.Orders and get an IQueryable (or IEnumerable depending on
the context) of all the orders that customer has placed.
This is all super-rad and a big time-saver...
Until you want to databind declaratively. Then it's slightly thorny.
You might think that if you have a Customer object on an Order object, and
you're in the context of a databinding to that Order object, you would be able
to say Customer.FirstName in, say, the DataField attribute of a GridView
BoundField for example, just as easily as you could say OrderID or whatever
else.
For some reason this isn't always the case.
That is to say, this will NOT work:
<asp:BoundField DataField="Customer.FirstName"
SortExpression="Customer.FirstName">
However, if you shove it just the tiniest bit towards the
imparative end of the scale and use a server tag in the body of a
TemplateField's ItemTemplate, then it DOES work.
<asp:TemplateField
SortExpression="Customer.FirstName">
<ItemTemplate>
<%# Eval("Customer.FirstName")
%>
</ItemTemplate>
Note the weird thing:
that you can still use it as a SortExpression straight from
markup.
I'm sure someone smarter than me knows exactly why this is the case, but I have no idea. Just the messenger on this one! But it probably has something to do with lazy-loading, so you should probably do some performance testing if you're doing this in a large-scale app. But that's generally true of LINQ anyway.