LINQ: Databinding in markup to a second-level property

by Grank August 25, 2008 16:43
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.

Tags: , , ,

Comments

Add comment


(Will show your Gravatar icon)

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen | Modified by Mooglegiant

About The Author

I'm a software developer and musician in Edmonton, AB.  I write mostly web-based software, primarily on the Microsoft stack.  I have an MCPD and several MCTS, but I've only been at this whole developer thing for a few years, and the truth is that I'm still learning more than knowing.  So these are my adventures and experiments and some of it will probably be blatantly wrong...  Just warning ya.