SQL Server Entity Framework get decimal out of range

wztqucjr  于 2023-06-21  发布在  其他
关注(0)|答案(1)|浏览(180)

Update:My question is "Why auto add zero", zero don't add by me.

My Entity

[Precision(11, 6)]
public decimal? EXCHANGE_RATE { get; set; }

My DTO

[Precision(11, 6)]
public virtual decimal? ExchangeRate { get; set; }

My Insert Data

6716844.89

Before AddAsync, the value is ok, but run AddAsync, throw exception,

InnerException {System.ArgumentException: Parameter value '6716844.890000' is out of range.

at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__188_0(Task`1 result)    
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()    
at System.Threading.Tasks.Task.<>c.<.cctor>b__272_0(Object obj)    
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) 
--- End of stack trace from previous location ---    
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)    
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread) 
--- End of stack trace from previous location ---    
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)    
at Microsoft.EntityFrameworkCore.Storage.Relatio…

Why the value become 6716844.890000, not 6716844.89 or 6716844.89000

Thanks

olmpazwi

olmpazwi1#

Your decimal value is out of range, because you have specified wrong precision:

[Precision(11, 6)] - Means Precision 11 and Scale 6

11 is max number of digits allowed in number (all including after point)

6 is the number of digits to the right of the decimal point in a number. It is guaranteed number of digits after decimal point and it is always reserved.

So, in your case before decimal point allowed only 5 digits.

In value 6716844.890000 you have 13 digits (7 integral digits + 6 after decimal point) and for handling this value your attribute should be:

[Precision(13, 6)]
public decimal? EXCHANGE_RATE { get; set; }

For further reading: Precision, scale, and length (Transact-SQL)

相关问题