我正在使用 ASP.NET 3.5 SP1,我有一个问题一直困扰着我。我有一个 ASPX 页面,上面有 2 个中继器控件,其中 1 个嵌套在另一个中。从后面的代码中,我有一个简单的 LINQ To Entities 查询来检索数据,然后我将此数据绑定到转发器控件。ASPX 页面如下所示:
<asp:Repeater ID="rptrMain" runat="server">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" ></asp:Label>
<asp:Label ID="lblDescription" runat="server"></asp:Label>
<asp:Repeater Runat="server" ID="rptrSub">
<ItemTemplate>
<asp:Label ID="lblPartName" runat="server" ></asp:Label>
<asp:Label ID="lblManufacturerName" runat="server" ></asp:Label>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
我将数据绑定到后面代码中的转发器,如下所示:
var q = from inventories in itemContext.Inventory.Include("Parts.Manufacturer")
select inventories;
List<Inventory> inventoryList = q.ToList();
rptrMain.DataSource = inventoryList ;
rptrMain.ItemDataBound += new RepeaterItemEventHandler(rptrMain_ItemDataBound);
rptrMain.DataBind();
void rptrMain_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Inventory inventory = e.Item.DataItem as Inventory;
Label lblName = e.Item.FindControl("lblName") as Label;
Label lblDescription = e.Item.FindControl("lblDescription") as Label;
lblName.Text = inventory.Name;
lblDescription.Text = inventory.Description;
Repeater rptrSub = e.Item.FindControl("rptrSub") as Repeater;
rptrSub.DataSource = inventory.Parts;
rptrSub.ItemDataBound += new RepeaterItemEventHandler(rptrSub_ItemDataBound);
rptrSub.DataBind();
}
}
void rptrSub_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Part part = e.Item.DataItem as Part;
Label lblPartName = e.Item.FindControl("lblPartName ") as Label;
Label lblManufacturerName = e.Item.FindControl("lblManufacturerName") as Label;
lblPartName.Text = part.Name;
lblManufacturerName.Text = part.Manufacturer.Name
}
}
库存与零件具有一对多关系,零件与制造商具有多对一关系。
现在我的问题是:如何在 LINQ 查询中过滤 Inventory 的子实体?例如,我只想检索属于某个 PartType 的所有 Parts。像这样:
where parts.Type == Tire
我确实发现了这个有用的提示http://blogs.msdn.com/b/alexj/archive/2009/06/02/tip-22-how-to-make-include-really-include.aspx 虽然那仍然没有允许我过滤子实体吗?