【发布时间】:2017-10-06 17:41:16
【问题描述】:
我是 LINQ 的新手,对做一些简单的 LINQ 了解甚少。但现在,我所拥有的比我能做的更复杂。我已经创建了 SQL 语句,尝试过它并且它有效。但我无法将其翻译成 LINQ。
编辑:我尝试编写 linq 代码并创建了一个模型以将其显示到视图中。但是,我没有得到我想要的数据。我不知道我在哪里弄错了linq。请帮忙。
This are the tables involved, the output using SQL and output using LINQ
这是 SQL:
select oh.date, oh.id,
od.TotalAmount,
CASE when oh.Discount_level = 2
then ((od.TotalAmount / 1.12) * .2)
END as Discount,
(od.TotalAmount / 1.12) as VATSale,
((od.TotalAmount / 1.12) * .12) as VAT,
CASE when oh.Discount_level = 2
then ((od.TotalAmount / 1.12) * .8)
when oh.Discount_level = 1
then od.TotalAmount
END as AmountDue
from Order_Header oh
inner join
(
select Order_Header_id, SUM(price * quantity) as TotalAmount
from Order_Details
group by Order_Header_id
) od
on oh.id = od.Order_Header_id;
我拥有的 linq:
var list = (from oh in db.Order_Header
join iq in (
from t in db.Order_Details
group t by t.Order_Header_id
into g
select new
{
ohId = g.Key,
totalAmount = ((from t2 in db.Order_Details select t2.price * t2.quantity)).Max()
}
)
on oh.id equals iq.ohId
select new Report
{
date = oh.date,
ohId = iq.ohId,
totalAmount = iq.totalAmount,
discount = oh.Discount_level == 2 ? (iq.totalAmount /1.12) * 2 : 0 ,
VATSale = iq.totalAmount / 1.12,
VAT = (iq.totalAmount / 1.12) * .12,
amountDue = oh.Discount_level == 2 ? ((iq.totalAmount / 1.12) * .8) * 2 : iq.totalAmount
}).ToList();
报告模型:
public class Report
{
public DateTime? date { get; set; }
public int ohId { get; set; }
public double totalAmount { get; set; }
public double discount { get; set; }
public double VATSale { get; set; }
public double VAT { get; set; }
public double amountDue { get; set; }
}
【问题讨论】:
-
向我们展示您迄今为止为使用 LINQ 所做的尝试。任何努力都是好的。
-
嗯,有趣的是,它将涉及至少两个投影 (
.Select)。好吧,有些人需要在沉迷于此类查询之前看到您的努力。只是一点点线索,您可以在 linq 中放入内联条件 - 传说中的<condition> ? <if_pass> : <otherwise>,例如.Select(x => x.DiscountLevel == 2 ? ((x.TotalAmount / 1.12) * 0.8) : ....). -
另外,如果您发布
Order_Header和Order_Details的结构会有所帮助。 -
是的,我刚刚上传了一张桌子的照片。
-
好吧,我正在起草我的答案。哈哈。无论如何,编码愉快。
标签: sql-server asp.net-mvc linq