这是对另一个问题的答案部分中的这个问题的回应.
我有一个Orders集合,每个Order订购OrderItems的集合,每个OrderItem都有一个PartId.使用LINQ如何实现以下SQL语句:
1)选择具有特定零件ID的所有订单
SELECT * FROM Order WHERE Id in (SELECT OrderId FROM OrderItems WHERE PartId = 100)
2)选择Order.OrderNumber和OrderItem.PartName
SELECT Order.OrderNumber, OrderItem.PartName FROM Order INNER JOIN OrderItem ON Order.Id = OrderItem.OrderId WHERE OrderItem.partId = 100
3)选择Order.OrderNumber和整个OrderItem细节:
SELECT Order.OrderNumber, OrderItem.* FROM Order INNER JOIN OrderItem ON Order.Id = OrderItem.OrderId WHERE OrderItem.partId = 100
Robert Wagne.. 11
实际代码应该是
1)
var orders = from o in Orders where o.OrderItems.Any(i => i.PartId == 100) select o;
Any()方法返回一个bool,就像SQL"in"子句一样.这将得到所有订单,其中任何OrderItems的PartId为100.
图2a)
// This will create a new type with the 2 details required var orderItemDetail = from o in Orders from i in Orders.OrderItems where i.PartId == 100 select new() { o.OrderNumber, i.PartName }
这两个from子句就像一个内连接.
图2b)
// This will populate the OrderItemSummary type var orderItemDetail = from o in Orders from i in Orders.OrderItems where i.PartId == 100 select new OrderItemSummary() { OriginalOrderNumber = o.OrderNumber, PartName = i.PartName }
3)
// This will create a new type with two properties, one being the // whole OrderItem object. var orderItemDetail = from o in Orders from i in Orders.OrderItems where i.PartId == 100 select new() { OrderNumber = o.OrderNumber, Item = i }
由于"i"是TypeItem类型的对象,因此Item被创建为OrderItem.
实际代码应该是
1)
var orders = from o in Orders where o.OrderItems.Any(i => i.PartId == 100) select o;
Any()方法返回一个bool,就像SQL"in"子句一样.这将得到所有订单,其中任何OrderItems的PartId为100.
图2a)
// This will create a new type with the 2 details required var orderItemDetail = from o in Orders from i in Orders.OrderItems where i.PartId == 100 select new() { o.OrderNumber, i.PartName }
这两个from子句就像一个内连接.
图2b)
// This will populate the OrderItemSummary type var orderItemDetail = from o in Orders from i in Orders.OrderItems where i.PartId == 100 select new OrderItemSummary() { OriginalOrderNumber = o.OrderNumber, PartName = i.PartName }
3)
// This will create a new type with two properties, one being the // whole OrderItem object. var orderItemDetail = from o in Orders from i in Orders.OrderItems where i.PartId == 100 select new() { OrderNumber = o.OrderNumber, Item = i }
由于"i"是TypeItem类型的对象,因此Item被创建为OrderItem.