C# ASP.NET如何关联orderlist与products表并跨表查询RecipeLink数据
你代码里的核心错误是LINQ查询不能使用&&操作符同时指定两个表作为查询源,你可以选择以下两种方式实现关联查询:
方案1:使用导航属性查询(优先使用)
你的代码里已经用到了x.Product.ProductName,说明实体已经配置了外键关联,直接通过导航属性就能自动关联两张表,修正代码如下:
public partial class CancelOrder : System.Web.UI.Page { BraceletDataContext bc = new BraceletDataContext(); protected void Page_Load(object sender, EventArgs e) { string id = Request.QueryString["Id"]; lblOrderID.Text = id; Delivery de = bc.Deliveries.SingleOrDefault(x => x.OrderID == id); // 只需要从Order_Lists查询,导航属性会自动关联Products表 var s = from x in bc.Order_Lists where x.OrderID == id select new { x.OrderID, x.ProductID, x.Product.ProductName, x.ClassStatus, x.Timetable, x.Link, x.Trainer, x.Start, x.End, // 通过导航属性获取Products表的RecipeLink字段 x.Product.RecipeLink }; Repeater1.DataSource = s; Repeater1.DataBind(); } }
方案2:显式写JOIN关联
如果没有配置实体间的外键导航属性,可以手动写关联逻辑:
public partial class CancelOrder : System.Web.UI.Page { BraceletDataContext bc = new BraceletDataContext(); protected void Page_Load(object sender, EventArgs e) { string id = Request.QueryString["Id"]; lblOrderID.Text = id; Delivery de = bc.Deliveries.SingleOrDefault(x => x.OrderID == id); var s = from order in bc.Order_Lists // 关联条件:订单表的ProductID等于商品表的ProductID join product in bc.Products on order.ProductID equals product.ProductID where order.OrderID == id select new { order.OrderID, order.ProductID, product.ProductName, order.ClassStatus, order.Timetable, order.Link, order.Trainer, order.Start, order.End, product.RecipeLink }; Repeater1.DataSource = s; Repeater1.DataBind(); } }
表结构参考:

内容的提问来源于stack exchange,提问作者WEI ZHUANG GOH
相关产品推荐
相关产品推荐

