2016-05-17 57 views
1

我一直試圖從數據庫查詢中添加兩個值(它們是字符串)。我試圖解析它們並將它們添加到數據庫查詢中,但我不能。將字符串解析爲十進制和求和sql查詢

DB值:

Amount1:  -400 (string) 
Amount2:  400 (string) 

我需要(-400)+(400)0

我的代碼是這樣的:

var Result = Model.Fin.Where(*some conditions*).Sum(a => decimal.TryParse(a.Amount)); 

你能幫助請。

回答

0

TryParse需要一個out參數以及要解析的值,並且其返回值不是小數點,也是bool

所以,你應該使用的有效語法是

var models = Model.Fin.Where(some conditions).ToList(); 
var Result = models.Sum(a => decimal.Parse(a.Amount)) 
+0

它也不工作。 – moonyy88

+0

它拋出任何錯誤? –

+0

在EntityFramework.SqlServer.dll中發生類型'System.NotSupportedException'的異常,但未在用戶代碼中處理其他信息:LINQ to Entities不能識別方法System.Decimal Parse(System.String)'方法,並且此方法無法翻譯成商店表達式 – moonyy88

0

TryParse你的情況下把較長低效代碼:

var Result = Model.Fin 
    .Where(*some conditions*) 
    .AsEnumerable() // you'll need this as well (Linq to Sql doesn't support the next sum) 
    .Sum(a => { 
    decimal v; 

    if (!decimal.TryParse(a.Amount, out v)) 
     return 0.0M; // a.Amount can't be decimal, say, "bla-bla-bla" 

    return v; 
    } 

由於Sql的Linq can' t用decimal.TryParse創建查詢,您必須切換到Linq to Objects - AsEnumerable()提取的數據,並總結在客戶端

相關問題