Linq 输入字符串在 MVC 中的格式不正确

Linq Input string was not in a correct format in MVC

原来SQL老程序员编码的命令是这样的

SELECT ooe_general_id, SUM(CAST(CAST(amount AS money) AS float)) AS totalAppro, MAX(date) AS lastDate 
FROM  dbo.pmTA_OoeGeneralAppropriation

数据类型:字符串

Database Values
----------------
3,200,000.00
2916410
28,710,000.00
0.80000000000291
-1000000

当我尝试将以上代码转换为 Linq 时,错误 'Input string was not in a correct format' 显示在这一行

totalAppro = g.Sum(p => Convert.ToDouble(p.amount))

我尝试将代码更改为

Convert.Double(string, IFormatprovider)  
Convert.ToDouble(String.Format("{0:c}", p.amount)) 
Convert.ToDecimal(p.amount.Replace(",",""))

来自这些 Currency, Convert, SUM LINQ 论坛,但错误仍然存​​在。

问题是我做错了什么?为什么我的前两个代码有效,但这个不行?最后,为什么会出现 'Input string was not in a correct format' 错误?

提前致谢。

更新

var totalAppropriationGeneralFund = (from p in db.iBudget_OoeGeneralAppropriation   
                                 where !p.amount.StartsWith("-")
                                 group p by p.ooe_general_id into g    
                                 select g).AsEnumerable().Select(g => new {
                                 id = g.Key,
                                 totalAppro = g.Sum(p => Convert.ToDecimal(p.amount.Replace(",",""))),
                                 date = g.Max(p => p.date)
                             }).ToList();

首先

不要将数据类型存储或转换为字符串,然后再返回。让它们保持原样,仅出于显示目的转换它们,绝对不要将数字类型作为字符串存储在数据库中(只是一个提示)。

其次

如果您有点担心准确性,请不要使用像 doublefloat 这样的浮点值。他们因失去精度和添加人工制品而臭名昭著,请使用 decimal

第三次

NumberStyles Enumeration : Determines the styles permitted in numeric string arguments that are passed to the Parse and TryParse methods of the integral and floating-point numeric types.

以上是你的问题

工作示例

var list = new List<string>
   {
      "3,200,000.00",
      "2916410",
      "28,710,000.00",
      "0.80000000000291",
      "-1000000"
   };

var sum = list.Sum(x => decimal.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture));

输出

33826410.80000000000291

Full Demo here

进一步阅读

decimal (C# Reference)

更新

Bagus Tesa 的评论所述,您不能在 EF 或 Linq 中使用 parse 方法 sql,这必须在内存中完成,我会考虑在 laying datatype 和/或 query

下更改你