Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform SUM operation in Entity Framework

I have a table.

create table tblCartItem(
pkCartItemId int primary key identity,
CartId int not null,
ProductId int not null,
Quantity int not null,
Price nvarchar(15)
)

and I want to perform sum opeartion on that like as

Select SUM(Price) from tblCartItem where CartId='107'

and I am trying to following code but its not working

ObjTempCart.CartTotal = (from c in db.tblCartItems where c.CartId == cartId select c.Price).Sum();

Any one help me to do this using Entity Framework. I am using MVC 4 Razor.

like image 347
Durgesh Pandey Avatar asked Aug 13 '16 09:08

Durgesh Pandey


2 Answers

May be You can use lambda Expression

var total=db.tblCartItems.Where(t=>t.CartId == cartId).Sum(i=>i.Price);
like image 115
hemantsharma Avatar answered Sep 18 '22 06:09

hemantsharma


Decimal.parse not working, try Convert.toDouble

double total = _context.Projecao
      .Where(p => p.Id == idProj)
      .Select(i => Convert.ToDouble(i.ValorTotal)).Sum();
like image 33
Diego Venâncio Avatar answered Sep 21 '22 06:09

Diego Venâncio