[英]C# EntityFramework Join
I would like to join the results of 2 entities based on the quantities. 我想加入基于数量的2个实体的结果。 Here's what I have...
这就是我所拥有的...
Order Ticket #1 订购票证#1
OrderID CustomerID ItemID Description POS# Cost Quantity
1 1 1 Apples 111 1.25 3
1 1 2 Oranges 222 1.12 5
1 1 3 Bananas 333 1.17 5
Order Ticket #2 订购票证#2
OrderID CustomerID ItemID Description POS# Cost Quantity
2 1 1 Apples 111 1.25 7
2 1 2 Oranges 222 1.12 2
2 1 3 Bananas 333 1.17 5
Here is the code I use to get each ticket: 这是我用来获取每张票证的代码:
public OrderEntity getOrder(int orderId)
{
var data = from c in Orders
where c.OrderID == orderId
select c;
return data;
}
How would I write the LINQ code to combine the 2 tickets so I get a Sum of the quantities? 我将如何编写LINQ代码以合并两张票证,从而得出数量的总和? It should look like this...
它应该看起来像这样...
Order Tickets #1 and #2 订购票证#1和#2
CustomerID ItemID Description POS# Cost Quantity
1 1 Apples 111 1.25 10
1 2 Oranges 222 1.12 7
1 3 Bananas 333 1.17 10
It seems like I should be able to do something like so... 看来我应该可以做这样的事情...
public List<OrderEntity> getCustomerOrders(int customerId)
{
var data = from c in Orders
where c.CustomerID == customerId
select c;
return data.ToList();
}
The problem is I cannot figure out the grouping. 问题是我无法弄清楚分组。 There is a lot of info about there about how to write the EF code for grouping, but I'm not sure if I should be grouping on CustomerID or on the Quantity.
关于如何编写用于分组的EF代码的信息很多,但是我不确定是否应该在CustomerID或数量上进行分组。 Any tips on how to do the grouping here would be greatly appreciated.
在这里如何进行分组的任何提示将不胜感激。
You should group by CustomerID
and ItemID
: 您应该按
CustomerID
和ItemID
分组:
Try something like this: 尝试这样的事情:
public List<OrderEntity> getCustomerOrders(int customerId)
{
var data = from c in Orders
where c.CustomerID == customerId
group c by new { c.CustomerID, c.ItemID } into g
select new OrderEntity () {
CustomerID = g.Key.CustomerID,
ItemID = g.Key.ItemID,
Quantity = g.Sum(x => x.Quantity)
};
return data.ToList();
}
I'm not sure how you define your data, but if you need to have Description
POS
, Cost
in your result, try: 我不知道你如何定义你的数据,但如果你需要有
Description
POS
, Cost
在你的结果,请尝试:
public List<OrderEntity> getCustomerOrders(int customerId)
{
var data = from c in Orders
where c.CustomerID == customerId
group c by new { c.CustomerID, c.ItemID,c.Description,c.POST,c.Cost } into g
select new OrderEntity () {
CustomerID = g.Key.CustomerID,
ItemID = g.Key.ItemID,
Quantity = g.Sum(x => x.Quantity),
Description = g.Key.Description,
POST = g.Key.POST,
Cost = g.Key.Cost
};
return data.ToList();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.