一个查询中 用到了 sum , 可是返回结果的小数有很多位 , 都不准确了..类似js中的小数运算一样...不太熟悉C#,不知道这问题是因为double的关系 , 还是因为代码写的问题 ,
通过 sql server profile 获取的sql语句执行后都是没有问题的
这是我的代码:
var query = db.SupDataGreenAccount1 .Where(lambda) .GroupBy( p => new{ p.ObjPos , p.District , p.Feature }) .Select( p => new {
//area是 double , 数据库中是 float sums = p.Sum(c => (double?)c.Area ?? 0), objpos = p.Key.ObjPos , district = p.Key.District , feature = p.Key.Feature }); var ss = query.ToArray(); var list = query.ToList();
这是调试中获取的数据:
这是 sql server profile 执行的sql:
SELECT 1 AS [C1], [GroupBy1].[A1] AS [C2], [GroupBy1].[K1] AS [ObjPos], [GroupBy1].[K3] AS [DISTRICT], [GroupBy1].[K2] AS [FEATURE] FROM ( SELECT [Extent1].[ObjPos] AS [K1], [Extent1].[FEATURE] AS [K2], [Extent1].[DISTRICT] AS [K3], SUM([Extent1].[AREA]) AS [A1] FROM [dbo].[Sup_Data_GreenAccount_1] AS [Extent1] WHERE (1 = 1) AND (( CAST(CHARINDEX([Extent1].[DISTRICT], N'保税区') AS int)) > 0) GROUP BY [Extent1].[ObjPos], [Extent1].[FEATURE], [Extent1].[DISTRICT] ) AS [GroupBy1]
这是执行上面的SQL返回的结果:
恩,已经知道 C# 存在 double相加精度不正确的问题...可是这个如何解决?
最好是能 在 lambda 中如何写就可以搞定?
其他的话 ..在 tolist 后再进行转换?
是double类型的问题,可以使用decimal类型来解决
也就是把
sums = p.Sum(c => (double?)c.Area ?? 0)
这句代码改为
sums = p.Sum(c => (decimal)((double?)c.Area ?? 0))
刚试了一下...还是有错误
由于无法推断出要求的精度和小数位数信息,因此 LINQ to Entities 查询不支持强制转换为 Decimal。
代码是:
var query = db.SupDataGreenAccount1 .Where(lambda) .GroupBy( p => new{ p.ObjPos , p.District , p.Feature }) .Select(p => new { sums = p.Sum(c => (decimal)((double?)c.Area ?? 0)), objpos = p.Key.ObjPos , district = p.Key.District , feature = p.Key.Feature });
...
@让你笑了: 试试先查询后合计
var query = db.SupDataGreenAccount1 .Where(lambda) .GroupBy( p => new{ p.ObjPos , p.District , p.Feature }) .ToList() .Select(p => new { sums = p.Sum(c => (decimal)((double?)c.Area ?? 0)), objpos = p.Key.ObjPos , district = p.Key.District , feature = p.Key.Feature });
@诶碧司: 恩,试过了..先查询后合计..这样数据是正确的...谢谢啦!!!!
刚搜到了一个办法...AsEnumerable 应该跟先tolist是一样的...http://social.msdn.microsoft.com/Forums/en-US/de17627b-6728-44a2-a2c2-516dd44641dc/converttodecimal-not-supported-by-linq-to-entities
不过我试了一下..都可以获得正确的数...而且效率会比tolist高些(仅仅从sql server profiler中的数据看) , 不知道是确实有性能 , 还是我理解错误了...
下面是两个代码:
var query = db.SupDataGreenAccount1 .Where(lambda) .GroupBy( p => new{ p.ObjPos , p.District , p.Feature }) .Select(p => new { sums = p.Sum(c => (double?)c.Area ?? 0), key = p.Key }) .AsEnumerable() .Select(c => new { sums = Convert.ToDecimal(c.sums) , objpos = c.key.ObjPos , district = c.key.District , feature = c.key.Feature }); var query1 = db.SupDataGreenAccount1 .Where(lambda) .GroupBy(p => new{p.ObjPos,p.District,p.Feature}) .ToList() .Select(p => new { sums = p.Sum(c => (decimal)((double?)c.Area ?? 0)), objpos = p.Key.ObjPos, district = p.Key.District, feature = p.Key.Feature });
@诶碧司: 又试了一下..其实没嘛区别...应该不存在我上面说的性能啥问题