LINQ中的嵌套查询结果(或子查询)
本文关键字:查询 结果 嵌套 LINQ | 更新日期: 2023-09-27 18:20:36
我有两个类:OrderDTO和ProductsDTO。
public class OrderDTO
{
// Attributes
public int OrderID { get; set; }
public DateTime OrderDate { get; set; }
public int EmployeeID { get; set; }
// Collection of Products
List<ProductDTO> Products { get; set; }
}
public class ProductsDTO
{
// Attributes
public int ProductID { get; set; }
public string Name { get; set; }
}
我还有表格:订单、产品和产品订单。
我想选择带有关联产品的订单,并在一个查询中返回它们。
示例:
using(var ctx = new Database())
{
return from o in ctx.Orders
join po in ctx.ProductOrder on o.OrderID equals po.OrderID
where o.OrderID == 1
select new OrderDTO
{
OrderID = o.OrderID,
OrderDate = o.OrderDate,
EmployeID = o.EmployeeID,
Products = (new ProductDTO
{
ProductID = po.ProductID,
Name = po.Name
}).ToList();
}
}
我想用订单属性填充OrderDTO,也用Products填充集合。
由于您希望联接返回匹配项的集合,而不是为每对创建一个新项,因此您希望执行GroupJoin
而不是Join
。不过,synatrx非常相似。
using(var ctx = new Database())
{
return (from o in ctx.Orders
join po in ctx.ProductOrder on o.OrderID equals po.OrderID
into products
where o.OrderID == 1
select new OrderDTO
{
OrderID = o.OrderID,
OrderDate = o.OrderDate,
EmployeID = o.EmployeeID,
Products = products.Select(po => new ProductDTO
{
ProductID = po.ProductID,
Name = po.Name
}).ToList();
}).ToList();
}
还要注意,在实际获取查询结果之前,您当前正在处理数据库。在处理上下文之前,您需要具体化查询的结果。
(from o in ctx.Orders
where o.OrderID == 1
select new OrderDTO
{
OrderID = o.OrderID,
OrderDate = o.OrderDate,
EmployeID = o.EmployeeID,
Products = from p in o.Products select
new ProductDTO
{
ProductID = p.ProductID,
Name = p.Name
};
}).ToList();
您可以简单地使用Order
和Product
之间的关系,因此不需要显式联接。此外,您不能在查询中执行.ToList()
,因此需要在dto对象中生成products
到IEnumerable
。
public class OrderDTO
{
// Attributes
public int OrderID { get; set; }
public DateTime OrderDate { get; set; }
public int EmployeeID { get; set; }
// Collection of Products
IEnumerable<ProductDTO> Products { get; set; }
}