I have written an SQL query which works fine. I need its equivalent query in LINQ MVC.
select sum(od.QUANTITY*od.PRODUCT_PRICE)
from ORDERS as o
inner join ORDER_DETAILS as od
on o.ID = od.ORDER_ID where o.IS_DELIVERED = 1
AND o.IS_CANCELED = 0;
I tried to form it myself and ended up with the query mentioned below, but it's not working for me;
var sum = from order in dbContext.ORDERS
join orderDetails in dbContext.ORDER_DETAILS
on order.ID equals orderDetails.ORDER_ID
where order.IS_DELIVERED == true && order.IS_RETURNED_BACK == false
select new { sum = dbContext.ORDER_DETAILS.Sum(od => od.QUANTITY * od.PRODUCT_PRICE) };
If your DbContext has proper relational mappings, the below code works
dbContext.ORDERS.ORDER_DETAILS
.Where(x => x.IS_CANCELLED == 0 && o.IS_RETURNED_BACK == false)
.Sum(od => od.PRODUCT_PRICE)
If it doesn't you need to use join
var result = (from o in dbContext.ORDERS
join od in dbContext.ORDER_DETAILS
on o.ID equals od.ORDER_ID
where o.IsCancelled == 0 && && o.IS_RETURNED_BACK == false
select od.PRODUCT_PRICE).Sum();
Is this what you meant to do? This will create a list of order detail total and then sum the list to give you a value.
var sum = (from order in dbContext.ORDERS
join orderDetails in dbContext.ORDER_DETAILS
on order.ID equals orderDetails.ORDER_ID
where order.IS_DELIVERED == true && order.IS_RETURNED_BACK == false
select new { orderDetailTotal = od.QUANTITY * od.PRODUCT_PRICE) }).Sum(x => x.orderDetailTotal);
Ideally, the ORDERS
object should have a list of ORDER_DETAILS
if done with proper relational mappings. Also the IS_DELIVERED
and IS_RETURNED_BACK
should be Booleans if mapped properly. In that case, you don't need an explicit join and your C# LINQ can be as simple as:
var sum = (from o in dbContext.ORDERS
where o.IS_DELIVERED && !o.IS_RETURNED_BACK
select new { Total = o.ORDER_DETAILS.QUANTITY * o.ORDER_DETAILS.PRODUCT_PRICE }
).Sum(x => x.Total);
Also, ideally the objects should've been named in pascal-case and without the underscores.
You don't need select clause, you can use Sum function on query result and specify lambda expression for field calculation you need.
var sum = (from order in dbContext.ORDERS
join orderDetails in dbContext.ORDER_DETAILS
on order.ID equals orderDetails.ORDER_ID
where order.IS_DELIVERED == true && order.IS_RETURNED_BACK == false).Sum(x=> x.QUANTITY * x.PRODUCT_PRICE)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.