2015-06-29 2 views
0

Я использую базу Entity (6.1.3) ()) для одного из моих проектов, где у меня есть три таблицы в базе данных, которая содержит десятичные поля.Основополагающая основа десятичной точности

Десятичные поля установлены с точностью 18 и масштабом 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; 
+0

Возможный дубликат [Десятичная точность и масштаб в EF Code First] (http://stackoverflow.com/questions/3504660/decimal-precision-and-scale-in-ef-code-first) - метод, используемый здесь то же самое, вам просто нужно переопределить OnModelCreating. – user1666620

+0

Я пробовал использовать modelBuilder, но кажется, что это проигнорировано. Например: 'modelBuilder.Entity (). Свойство (x => x.Price) .HasPrecision (18, 5);' –

+0

вы делаете это в нужном месте в модели? можете ли вы добавить образец кода, где вы добавили этот код к вопросу? – user1666620

ответ

0

Если округление не вариант, вы можете повысить точность и масштаб поля базы данных на C# макс (28-29 как в docs). Как десятичная (29, 20).

+0

Это сработало, спасибо Алекс! –

Смежные вопросы