How to perform SUM operation in Entity Framework - asp.net-mvc

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.

May be You can use lambda Expression
var total=db.tblCartItems.Where(t=>t.CartId == cartId).Sum(i=>i.Price);

its working try this..
use Decimal.Parse to convert price.
ObjTempCart.CartTotal = db.tblCartItems.Where(t=>t.CartId == cartId).Select(i=>Decimal.Parse(i.Price)).Sum();

Finally I have a solution of that but its not exactly from Entity Framework, But its working...
private double CartItemTotalPrice(Int32 CartID)
{
List<string> pricelst = new List<string>();
pricelst = (from c in db.tblCartItems where c.CartId == CartID select c.Price).ToList();
double Total = 0;
if (pricelst != null)
{
for (int i = 0; i < pricelst.Count; i++)
{
Total += Convert.ToDouble(pricelst[i]);
}
}
return Total;
}

Decimal.parse not working, try Convert.toDouble
double total = _context.Projecao
.Where(p => p.Id == idProj)
.Select(i => Convert.ToDouble(i.ValorTotal)).Sum();

Related

GROUP BY LINQ ASP.NET MVC

Let's suppose we have a Linq query like this:
int companyID = Convert.ToInt32(((UserIdentity)User.Identity).CompanyId);
var stock = from i in _stockService.GetStock()
join ur in _inventoryService.GetInventory() on i.ProductID equals ur.Id
where ur.ComapnyId == companyID
select new StockVM
{
Product = ur.ItemName,
Quantity = i.Quantity,
BatchID = i.BatchID,
StockStatus = i.StockStatus,
MfgDate = i.MfgDate,
ExpDate = i.ExpDate,
};
Result
How to do a "Group By Product" with sum of Quantity in this linq query?
I need to only get max ExpDate firstOrDefault
try something like this:
int companyID = Convert.ToInt32(((UserIdentity)User.Identity).CompanyId);
var stock = from i in _stockService.GetStock()
join ur in _inventoryService.GetInventory() on i.ProductID equals ur.Id
where ur.ComapnyId == companyID
group new { Quantity = i.Quantity } by new { ur.ItemName } into g
select new { Product = g.Key, TotalQuantity = g.Sum() } ).ToList() ;
List<StockVM> _lst = new List<StockVM>();
foreach(var item in stock ){
StockVM row = new StockVM();
row.Product = item.ItemName;
//....
_lst.Add(row);
}

How do I check how many times a group of value has appeared under a certain date/weekday in Entity Framework

I want a way to check the max and the min times a ticket has been called at a certain weekday (eg: Monday: 5 tickets max; 2 min), the ticket has an ID that ranges between 0 and 4 so I want them all to be noticed.
This is what I currently have:
int S = 0;
var senhas = _db.SenhaSet.ToList();
double[] countersemana = new double[20];
foreach (var senha in senhas)
{
if (senha.Data.DayOfWeek == DayOfWeek.Monday && senha.IdTipoSenha >= 0)
{
S++;
break;
}
}
Your code is very inefficient as it relies on returning the entire SenhaSet table from the database and then looping round it. You want to apply the filter via Entity Framework on the database. Something like (I don't know your column names so am guessing):
var senhas = _db.SenhaSet
.Where(s => SqlFunctions.DatePart("dw", s.Data) == DayOfWeek.Monday && IdTipoSenha >= 0)
.GroupBy(s => DbFunctions.TruncateTime(s.Data))
.Select(s => new {
TicketDate= s.Key,
Count = s.Count(t => t.IdSenha)
})
.ToList();
int maxTickets = senhas.Max(s => s.Count);
int minTickets = senhas.Min(s => s.Count);
This assumes the database is SQL Server in order to use the System.Data.Objects.SqlClient.SqlFunctions.DatePart method.

Result of MAX()- method

I have table tb_Orders (it empty), which have fields^
- order_id (int) (primary key)
- order_date nchar(30)
In my application, when client make order, requests the function:
private int GetNewOrderId()
{
int ord_id = 0;
if (db.tb_Orders.Max(x => x.order_id) != null)
{
int ord = db.tb_Orders.Max(x => x.order_id);
ord_id = ord + 1;
}
else
{
ord_id = 1;
};
return ord_id;
}
which get the new order id (+1 to max order in table).
Operator "if" must, when the table is still empty, get id = 1;
But the result - error (when I try to get id).
ERROR TEXT: "Error converting cast a value type "Int32", as materialize value is null."
Try casting your order_id to a nullable integer when making the Max call:
private int GetNewOrderId()
{
int nextOrderId = db.tb_Orders.Max(x => (int?)x.order_id) ?? 1;
return nextOrderId;
}
You will also notice that in my example there's only a single SQL query to the database whereas you were making 2: one in the if statement and another one inside.
It seems your order_id is Nullable<int>. Use the Value property to get it's value, and you can also perform the query before if statement and don't execute the query twice:
var max = db.tb_Orders.Max(x => x.order_id);
if(max != null)
{
int ord = max.Value;
ord_id = ord + 1;
}

The SqlParameter is already contained by another SqlParameterCollection

I'm using EF DbContext SqlQuery to get a list of paged objects using PagedList (https://github.com/TroyGoode/PagedList) and I'm getting the following error:
"The SqlParameter is already contained by another SqlParameterCollection"
Here's my repository code:
var db = (DbContext)DataContext;
const string sqlString =
#"
WITH UserFollowerList
AS
(
SELECT uf.FollowId
FROM UserFollow uf
WHERE uf.UserId = #UserId
)
SELECT * FROM UserFollowerList uf
INNER JOIN [User] u ON uf.FollowId = u.UserId
WHERE IsDeleted = 0
"
;
var userIdParam = new SqlParameter("UserId", SqlDbType.Int) {Value = userId};
var userList =
db.Database.SqlQuery<User>(sqlString, userIdParam)
.ToPagedList(pageIndex, pageSize);
return userList;
But when I call the ToList extension on the SqlQuery statement it works fine:
var userList = db.Database.SqlQuery<User>(sqlString, userIdParam).ToList();
PagedList code:
private PagedList(IQueryable<T> source, int pageIndex, int pageSize)
{
TotalItemCount = source.Count();
PageSize = pageSize;
PageIndex = pageIndex;
PageCount = TotalItemCount > 0 ? (int)Math.Ceiling(TotalItemCount / (double)PageSize) : 0;
HasPreviousPage = (PageIndex > 0);
HasNextPage = (PageIndex < (PageCount - 1));
IsFirstPage = (PageIndex <= 0);
IsLastPage = (PageIndex >= (PageCount - 1));
ItemStart = PageIndex * PageSize + 1;
ItemEnd = Math.Min(PageIndex * PageSize + PageSize, TotalItemCount);
// add items to internal list
if (TotalItemCount > 0)
Data = pageIndex == 0 ? source.Take(pageSize).ToList() : source.Skip((pageIndex) * pageSize).Take(pageSize).ToList();
}
I've already the solution below without any success:
var param = new DbParameter[] { new SqlParameter { ParameterName = "UserId", Value = userId }
What can I do to fix the error I'm experiencing?
FYI I just saw this exact same error message when using an EF 5 DbContext to call context.ExecuteQuery<my_type>(...); with an array of SqlParameters, where my_type had a string but the SQL statement was returning an int for one of the parameters.
The error was really in the return mapping, but it said the SqlParameter was to blame, which threw me off for a little while.
When using a generic call to SqlQuery such as db.Database.SqlQuery you must iterate to the last record of the returned Set in order for the result set and associated parameters to be released. PagedList uses source.Take(pageSize).ToList() which will not read to the end of the source set. You could work around this by doing something like foreach(User x in userList) prior to returning the result.
I tried the following solution from Diego Vega at http://blogs.msdn.com/b/diego/archive/2012/01/10/how-to-execute-stored-procedures-sqlquery-in-the-dbcontext-api.aspx and it worked for me:
var person = context.Database.SqlQuery<Person>(
"SELECT * FROM dbo.People WHERE Id = {0}", id);
When you are using parameters on (SqlQuery or ExecuteSqlCommand) you can't use theme by another query until old query dispose.
in PagedList method you use "source.Count();" at first and the end line you are using "source" again. that's not correct.
you have 2 solution.
1- send param to PagedList Method and new theme for each using SqlQuery or ExecuteSqlCommand
2-remove PagedList and send your paging param to SqlQuery or ExecuteSqlCommand like this :
const string sqlString =
#"
WITH UserFollowerList
AS
(
SELECT uf.FollowId,ROW_NUMBER() OVER(ORDER BY uf.FollowId ) RowID
FROM UserFollow uf
WHERE uf.UserId = #UserId
)
SELECT * FROM UserFollowerList uf
INNER JOIN [User] u ON uf.FollowId = u.UserId
WHERE IsDeleted = 0 and RowID BETWEEN (((#PageNumber- 1) *#PageSize)+ 1) AND (#PageNumber * #PageSize))
"
;
Just encountered this exception even though it was my first query to the database with a single param. And having the Context in a 'using'.
When I 'hardcoded' the queryparameter valies into the string it worked correct for some reason. But as soon as I used SqlParameter it gave me the "The SqlParameter is already contained by another SqlParameterCollection"
This didn't work:
context.Database.SqlQuery<int?>(query, new SqlParameter("#TableName", tableName));
This did:
context.Database.SqlQuery<int>(query, new SqlParameter("#TableName", tableName));
The difference being the return type int? vs int. So for anyone reading this. Please also check your return type of the SqlQuery even when you're sure it should work.
This is old, but I ran into the same problem and someone has thought of the solution here
https://dotnetfiddle.net/GpEd95
Basically you need to split this up into a few steps in order to get your paged query
//step 1 set the page numbers
int pageNumber = 1;
int pageSize = 2;
//step 2 set your parameters up
var parm2 = new SqlParameter("param1", "Kevin");
var parm1 = new SqlParameter("param1", "Kevin");
var pageParm = new SqlParameter("#p2", (pageNumber - 1) * pageSize);
var pageSizeParm = new SqlParameter("#p3", pageSize);
//step 3 split your queries up into search and count
var sqlString = #"SELECT FT_TBL.*
FROM EquipmentMaintenances AS FT_TBL
INNER JOIN FREETEXTTABLE(vw_maintenanceSearch, Search, #param1) AS KEY_TBL ON FT_TBL.EquipmentMaintenanceID = KEY_TBL.[KEY]
WHERE FT_TBL.Status = 1
ORDER BY RANK DESC, FT_TBL.EquipmentMaintenanceID DESC OFFSET #p2 ROWS FETCH NEXT #p3 ROWS ONLY";
var sqlCountString = #"SELECT COUNT(1)
FROM EquipmentMaintenances AS FT_TBL
INNER JOIN FREETEXTTABLE(vw_maintenanceSearch, Search, #param1) AS KEY_TBL ON FT_TBL.EquipmentMaintenanceID = KEY_TBL.[KEY]
WHERE FT_TBL.Status = 1
";
//step 4 run your queries c# doesn't like the reusing of parameters so create 2 (e.g Kevin) so your results will run correctly.
var main = _db.Database.SqlQuery<EquipmentMaintenance>(sqlString, parm1, pageParm, pageSizeParm).ToList();
var count = _db.Database.SqlQuery<int>(sqlCountString, parm2).FirstOrDefault();
//step 5 created your paged object - I'm using x.pagedlist
var paged = new StaticPagedList<EquipmentMaintenance>(main, pageNumber, pageSize, count);
Obviously your now passing this back to your view or other function for display.

Include ENUM description in LINQ results

I have the following GROUP statement producing the results I am looking for.
However, I want to change line 4 below to "group s by s.ComplaintNatureTypeId.ToDescription()" so that the results are grouped by ENUM description rather than a numeric key value.
If I change the line I get the error "Method 'System.String ToDescription(System.Enum)' has no supported translation to SQL."
note: The ToDescription() is a Enum Extension method used to get description from enum.
var qry = from s in _db.Complaints
where s.Site.SiteDescription.Contains(searchTextSite)
&& (s.Raised >= startDate && s.Raised <= endDate)
group s by s.ComplaintNatureTypeId.ToString()
into grp
select new
{
Site = grp.Key,
Count = grp.Count()
};
return Json(qry.ToList(), JsonRequestBehavior.AllowGet);
The ENUM class :
using System.ComponentModel;
namespace Emas.Model.Enumerations
{
public enum ComplaintNatureType
{
[Description("- Please Select -")]
Blank = 0,
[Description("Letter")]
LE = 1,
[Description("eMail")]
EM = 2,
[Description("Verbal")]
VE = 3,
[Description("Other [see comments]")]
OT = 4,
}
}
You'll have to do the .ToDescription() in memory.
var qry = (from s in _db.Complaints
where s.Site.SiteDescription.Contains(searchTextSite)
&& (s.Raised >= startDate && s.Raised <= endDate)
group s by s.ComplaintNatureTypeId
into grp
select new
{
Site = grp.Key,
Count = grp.Count()
})
.ToList()
.Select(g => new
{
Site = g.Site.ToDescription(),
g.Count
});
return Json(qry, JsonRequestBehavior.AllowGet);

Resources