Binding entities with foreign key to datalist
I have the following code:
var devices = from d in ctx.Devices.Include("DeviceGroups")
where d.DeviceEnabled == true
select d;
dlTerminals.DataSource = devices;
On the front end I do the following:
<asp:DataList ID="dlTerminals" runat="server" DataKeyField="DeviceId" GridLines="None" Repe开发者_JAVA技巧atColumns="2" RepeatDirection="Horizontal" Width="100%">
<ItemTemplate>
<%# Eval("DeviceGroups.GroupName")%>
</ItemTemplate>
</asp:DataList>
But I get the following error:
does not contain a property with the name 'GroupName'.
Found a solution:
select new { d.DeviceId, d.MAC, d.DeviceType, d.LastConnectTime, d.DeviceGroups.FirstOrDefault().GroupName };
As you are developing asp.net flattening the data is probably the best solution. You may also consider adding a property to your class like
public string DeviceGroupName
{
get
{
return this.DeviceGroups.FirstOrDefault();
}
}
精彩评论