使用LINQ显示关联的表

时间:2011-12-06 13:31:10

标签: asp.net c#-4.0 gridview entity-framework-4 linq-to-entities

我正在使用Entity Framework模型。在LINQ的帮助下,我试图在一个查询中加载实体及其相关数据(即实现预先加载)。

以下是代码隐藏:

protected void btn5_Click(object sender, EventArgs e)
{
    using (EStoreEntities ctx5 = new EStoreEntities())
    {
        var query = (from o in ctx5.Order_Details.Include("Order") select o);
                                                           //Order -navigation property

        tb5.Text = (queryas ObjectQuery).ToTraceString();
        gv5.DataSource = query;
        gv5.DataBind();
    }
}

我正在使用以下ASP代码:

<asp:Button ID="btn5" runat="server" Text="Button" onclick="btn5_Click" />
<asp:GridView ID="gv5" runat="server"></asp:GridView>
<asp:TextBox ID="tb5" runat="server" TextMode="MultiLine"></asp:TextBox>

如何修复代码以使我的GridView控件中显示Order表内容? 提前谢谢。

1 个答案:

答案 0 :(得分:0)

protected void btn5_Click(object sender, EventArgs e)
{ 
    using (EStoreEntities ctx5 = new EStoreEntities())
    {
        var query = ctx5.Order_Details.Select(x => new { 
                                                      Col1 = x.AAA,
                                                      Col2 = x.BBB,
                                                      Col3 = x.Order.AAA
                                                   });

        tb5.Text = (query as ObjectQuery).ToTraceString();
        gv5.DataSource = query;
        gv5.DataBind();
    }
}