In code, with LINQ to SQL you can easily reference a column in a related table, but it seems like you can't do this when databinding controls.
In my case, I have a table called UnitOccupancy with a UnitID column that points to the primary key UnitID of the Units table. In code, if I want to access UnitCode in Units, from UnitOccupancy, I write Units.UnitCode. But I can't set the DataTextField of a DropDownList control to Units.UnitCode. It only seems to accept column references in the base table.
For example, this does not work:
< asp:DropDownList ID="unitDropdown" runat="server" DataSourceID="ldsUnitOccupancy"
DataValueField="UnitID" DataTextField="UnitCode" SelectedValue='<%# Bind("UnitID") %>' >
< / asp:DropDownList>
You might think I should create a LinqDataSource that points to the Units table, but here I hit another problem. I need to restrict the units to those where the UnitOccupancy table fulfills some criteria. In SQL I want to do this:
select u.UnitID, u.UnitCode
from Units u
join UnitOccupancy uo on u.UnitID=uo.UnitID
where uo.BranchID=@BranchID
If my LinqDataSource points to UnitOccupancy the Where clause works, but I can't get UnitCode. If my LinqDataSource points to Units I can get UnitCode, but I don't know how to make the Where clause work.
I have also tried programmatically setting the DataSource of the DDL to a stored procedure (created as a method in the .dbml) that runs the above SQL. However I can't seem to get this approach to work if the Bind function is used in the DDL (which is essential for the DDL to automatically update the UnitID value of my record).
Any suggestions?