c# - 当所有内容都设置为四位小数时, Entity Framework 四舍五入

标签 c# entity-framework-4 sql-server-2008-r2

我试图理解为什么 Entity Framework 4 在 EF 架构模型和数据库中将精度设置为 4 时四舍五入到两位小数。

这是我对小数字段之一的架构定义:

SellPrice specify a scale of 19,4

这是我的数据库定义

CREATE TABLE OrderItems(
....
[SellPrice] [decimal](19, 4) NOT NULL,
....

当我在计算产品的售价后执行插入查询时,我看到有足够的小数

SellPrice shows lots of decimals

MiniProfiler 显示我的查询并显示该值有小数

DECLARE ...
        @15 Decimal = '100,54347826086956521739130435',
        ...

insert [dbo].[OrderItems](..., [SellPrice], ...)
values (..., @15, ....)
select [OrderItemId]
from [dbo].[OrderItems]
where @@ROWCOUNT > 0 and [OrderItemId] = scope_identity()

但是当我查看 Microsoft Sql Profiler 时,SellPrice 是四舍五入的

exec sp_executesql N'insert [dbo].[OrderItems](..., [SellPrice], ...)
values (..., @15, ...)',
...,@15=100.54,...'

我很难找到四舍五入的值。

最佳答案

我猜,你的 SQL 数据类型应该是 money,而不是 decimal 因为 decimal 在 c# 中是 decimal SQL 不同。特别是,如果您查看 TSQL decimal 类型的 MSDN 文档 ( http://msdn.microsoft.com/en-us/library/ms187746.aspx) 是 states;

In Transact-SQL statements, a constant with a decimal point is automatically converted into a numeric data value, using the minimum precision and scale necessary. For example, the constant 12.345 is converted into a numeric value with a precision of 5 and a scale of 3.

Converting from decimal or numeric to float or real can cause some loss of precision.

没有明确说明这是您问题的原因,但我猜它是。 money 数据类型可能更幸运,因为它是最等价的,如果您从现有数据库生成模型,这也是 EF 的默认值

关于c# - 当所有内容都设置为四位小数时, Entity Framework 四舍五入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14966663/

相关文章:

entity-framework-4 - Entity Framework 中的 T CreateObject<T> 是否也会在创建代理后跟踪更改?

sql-server-2008-r2 - Entity Framework 代码第一基类未映射到数据库

c# - 为什么foreach循环里面的switch只执行一次

c# - 路由被映射到不同路由的参数

entity-framework - 将两个不同的实体映射到同一个表?

c# - 将 Entity Framework 4.4 与 Mysql 结合使用

SQL Server 2008 R2 DMV - sys.dm_sql_referencing_entities - 查询用法

sql-server - 使用 Python 连接到带有 Windows 身份验证的 MS SQL Server?

c# - 通过构建服务器 "unable to find version"进行 Nuget 还原

c# - 通过 C# 代码在远程机器上启动和停止 IIS