我想使用Linq选择一个对象,其中一个元素是一个数字,我想在运行时将其格式化为一个字符串。我想创建一个特定的描述文本,包括其他列的一些数据。如果你看一下select-sentence,我试着将字符串格式化为带有两位小数的货币,这是行不通的。我该如何正确地做到这一点?
var stuff = from obj in _dbc.Stuff
where
SqlMethods.Like(obj.SEGMENT2, "0023") &&
SqlMethods.Like(obj.SEGMENT4, "1243")
group obj by new
{
obj.SEGMENT1
}
into g
select new StuffObject
{
Item = g.Key.SEGMENT1,
Description =
string.Format("{0:C2}", g.Sum(p => p.VALUE == null ? 0 : p.VALUE.Value)) //<-- This is not working for me
+ "<br/>" + g.Min(p => p.DESCRIPTION),
DeCode = g.Min(p => p.SEGMENT2),
CeCode = g.Min(p => p.SEGMENT4),
QTY = g.Sum(p => p.QUANTITY == null ? 0 : (int)p.QUANTITY),
Cost = g.Sum(p => p.VALUE == null ? 0 : (double)p.VALUE)
};
顺便说一下,我收到的错误代码是:
System.InvalidOperationException: Could not translate expression .... abbreviated ...into SQL and could not treat it as a local expression.
我的StuffObject类现在(我还没试过@Grundy回答):
public class StuffObject
{
public string Item { get; set; }
public string Description { get; set; }
public string DeCode { get; set;}
public string CeCode { get; set; }
public int QTY{ get; set; }
public double Cost { get; set; }
}
答案 0 :(得分:1)
LINQ无法将string.Format
转换为SQL,因此您需要摆脱它。
您可以更改StuffObject
之类的
public class StuffObject{
....
private decimal sumValue;
private decimal description;
public string Description {
get{
return string.Format("{0:C2}<br/>{1:C2}", sumvalue,description);
}
}
....
}
然后像这样更改LINQ查询
....
select new StuffObject
{
Item = g.Key.SEGMENT1,
description =g.Min(p => p.DESCRIPTION),
sumValue =g.Sum(p => p.VALUE == null ? 0 : p.VALUE.Value),
DeCode = g.Min(p => p.SEGMENT2),
CeCode = g.Min(p => p.SEGMENT4),
QTY = g.Sum(p => p.QUANTITY == null ? 0 : (int)p.QUANTITY),
Cost = g.Sum(p => p.VALUE == null ? 0 : (double)p.VALUE)
};