3

I am currently converting a stored procedure from an old system by some old programmers into a linq but I can't figure out what is causing this error. The code is as follows:

Controller:

var ObligationRequestDetailsTotalCostByOoe = (from p in db.iBudget_ObligationRequestDetails
where p.ooe_general_id != null && p.is_approved == 1
group p by p.ooe_general_id into g
select new
{
id = g.Key,
amount = g.Sum(p => Convert.ToDouble(p.amount))
}).ToList();

Model:

public int id { get; set; }
public string amount { get; set; }

I tried to change Convert.ToDouble() to Double.Parse() but this error 'Single Parse(System.String)' showed. I tried to add 'System.Globalization.CultureInfo.InvariantCulture' after the p.amount but still the error persist.

What am I doing wrong here? Thanks in advance.

  • EF is trying to convert expression to SQL and there is no equivalent. – Nkosi Apr 18 '18 at 02:47
  • @Nkosi what turn around can I do here? I tried to do the tips here = https://www.c-sharpcorner.com/blogs/exception-linq-to-entities-does-not-recognize-the-method-tostring but failed miserably – John Clarence Castro Apr 18 '18 at 02:53
  • @mjwills p.amount is a value from the model iBudget_ObligationRequestDetails which is as listed above, a string variable – John Clarence Castro Apr 18 '18 at 02:56
  • Split the query up before the grouping, use `AsEnumerable` and then you should be able to use the convert or parse method after – Nkosi Apr 18 '18 at 02:56
  • Why is it a string type if it is an amount? Is it possible to change the DB (and the C#) to be a different data type? – mjwills Apr 18 '18 at 02:57
  • @Nkosi Where should I add the AsEnumerable? I tried doing your suggestion earlier which looked like this amount = g.AsEnumerable().Sum(p => float.Parse(p.amount)) but error still showing – John Clarence Castro Apr 18 '18 at 02:58
  • @mjwills I don't know. The previous developers had this in their codes. The bad thing is that it has foreign keys so I can't change the datatype. – John Clarence Castro Apr 18 '18 at 02:59

1 Answers1

3

You will need to use AsEnumerable so as to work with the records in memory after it has been returned from the database. Then you will be able to use Convert.ToDouble

var ObligationRequestDetailsTotalCostByOoe = (from p in db.iBudget_ObligationRequestDetails
where p.ooe_general_id != null && p.is_approved == 1
group p by p.ooe_general_id into g
select g) // <-- db call
.AsEnumerable() //<-- memory call
.Select(g => new {
    id = g.Key,
    amount = g.Sum(p => Convert.ToDouble(p.amount))
})
.ToList();
Nkosi
  • 235,767
  • 35
  • 427
  • 472