0

Is someone able to please explain why EF doesn't round a decimal by default when the value been stored has more decimal places than the max decimal places in the DB field.

It would be common sense for any sort of application to round a decimal when the store-able decimals (decimals configured in the DB field) are shorter than the calculated value needed to be stored.

At the moment to me it seems as though EF is treating the decimal like a string and truncating the value when storing to the database table.

EDIT/Answer: For anyone struggling on this looking for an easy fix:

I was looking for something that disables truncating.

    public UnitOfWork(string connectionString)
    {
        DataContext = new DbContext(connectionString);
        SqlProviderServices.TruncateDecimalsToScale = false;
    }

The answer for this question here was exactly what was expected: Entity Framework Code First truncating my decimals

Community
  • 1
  • 1
Saleh
  • 150
  • 10
  • How are you expecting to round a number that is _more precise than the maximum amount of precision possible_? – Ian H. Feb 13 '17 at 14:47
  • I would expect 1.7777 > 1.78 to 2 decimal places, correct me if I am missing something. Thanks. – Saleh Feb 13 '17 at 14:49
  • My personal understanding of this would be, that the Environment cannot handle numbers with more decimal, because it cannot be stored as a `decimal`, and truncates it after the maximum number of places. – Ian H. Feb 13 '17 at 14:51
  • 1
    Neither rounding nor truncation are guaranteed to be the correct thing to do in all circumstances. You've now discovered that you're getting truncation, so if you want rounding, it's up to you to implement that. If your question was about how to achieve said rounding, it would be quite answerable, but at the moment, you're acting as if truncation is *obviously* wrong and asking *why* it's being done, which likely cannot be found. – Damien_The_Unbeliever Feb 13 '17 at 14:52
  • I can do a long winded solution around it but I would prefer some sort of handling by EF if possible in the background with out any code. – Saleh Feb 13 '17 at 14:52
  • Fair enough as probably expected it will be unlikely to get an answer or a solution other than manual intervention with custom code or some sort of field specific configuration in C# as it turns out so far in my investigation. – Saleh Feb 13 '17 at 14:56
  • Turns out truncating is currently in place to prevent older applications from breaking for backward compatibility: https://msdn.microsoft.com/en-us/library/system.data.entity.sqlserver.sqlproviderservices.truncatedecimalstoscale%28v=vs.113%29.aspx – Saleh Feb 13 '17 at 16:34

1 Answers1

2

Because truncating is the normal behaviour.
http://entityframework.codeplex.com/workitem/735

BarArp
  • 21
  • 3
  • Its normal behaviour in current versions only for backwards compatibility. What would be ideal is to disable it. – Saleh Feb 13 '17 at 16:47