Skullomania Skullomania - 4 months ago 30
C# Question

How do I properly convert a string to decimal in my linq query?

In my C# MVC 5 application, I am trying to use a linq query to convert a column in my sql server table that is an NVarChar to a decimal and display it in the view.

I know that if I was to do a simple SQL query or was using webforms I could simply do the following:

Select Sum(Cast(GrandTotal as decimal)) as GrandTotal From [myDB].[dbo].[Table]
WHERE Year = '2017'

How would I do this in linq? This is what I tried:

public ActionResult Total()
var model = (from p in db.Table
where p.Year.Equals("2017")
select decimal.Parse(p.GrandTotal)).Sum();

return View(model);

The error is as follows:
LINQ to Entities does not recognize the method 'System.Decimal Parse(System.String)' method, and this method cannot be translated into a store expression

Not a duplicate

The title is similar but the solution is different. In addition I was able to resolve the issue by use of the solution given. The question that you marked this as a duplicate of had no clear resolution


I'm unaware of a LINQ-To-Entities function that can do this. Id do it using LINQ-To-Objects:

var result = (from p in db.Table where "2017" == p.Year select p).ToList();
var model = (from p in result select decimal.Parse(p.GranTotal)).Sum();