[英]Entity framework decimal precision
我正在為其中一個項目使用Entity Framework(6.1.3)( 數據庫優先),在數據庫中我有三個包含十進制字段的表。
十進制字段的精度設置為18, decimal(18, 5)
為5,如下所示: decimal(18, 5)
我已經檢查了edmx XML文件,似乎小數點已按原樣映射。 即:
<Property Name="Price" Type="decimal" Precision="18" Scale="5" Nullable="false" />
但是,當我嘗試保存計算得出的十進制值(即28021.800000000000000000000002
,出現異常,告訴我該屬性值超出范圍。
實體框架不應該只保存此小數的精度和小數位數嗎? 如果沒有,我怎樣才能使我的十進制“有效”?
提前致謝 :-)
用代碼示例編輯:
// Loop through billing price lines on this billing
foreach (BillingPriceLine priceLine in billing.BillingPriceLines)
{
// Price line specification sum fields
decimal totalPriceLineSpecificationProduction = 0;
decimal totalPriceLineSpecificationSum = 0;
// Loop through billing price line specifications on this price line
foreach (BillingPriceLineSpecification specification in priceLine.BillingPriceLineSpecifications)
{
// First, check if the estimated production and realised production has a value
if (specification.EstimatedProduction.HasValue && specification.RealisedProduction.HasValue)
{
// Calculate production for a price line specification
specification.Production = specification.EstimatedProduction.Value - specification.RealisedProduction.Value;
// Add production to total price line specification production
totalPriceLineSpecificationProduction = specification.Production;
// Add to total price line specification sum
totalPriceLineSpecificationSum += specification.Production * specification.Price;
}
}
// Set total production on price line
priceLine.Production = totalPriceLineSpecificationSum;
// Set price on price line
priceLine.Price = totalPriceLineSpecificationProduction / priceLine.Production;
// Set total price on price line
priceLine.TotalPrice = (priceLine.Production * priceLine.Price) * 100;
}
// Set subtotal, VAT and total sum on billing
billing.Subtotal = billing.BillingPriceLines.Sum(x => x.TotalPrice);
billing.VAT = billing.Subtotal / 4;
billing.Total = billing.Subtotal + billing.VAT;
// Save changes in database
return ctx.SaveChanges() > 0;
如果不選擇舍入,則可以將數據庫字段的精度和范圍提高到C#max(如docs中的 28-29)。 像小數(29,20)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.