efcore icon indicating copy to clipboard operation
efcore copied to clipboard

A select into a decimal model translates to CAST([v].[Value] AS decimal(18,2)) (only two decimals recieved)

Open KaptenJon opened this issue 7 years ago • 7 comments

The statement select( new{decimalValue = (decimal) doubleValue}) translates into CAST([v].[Value] AS decimal(18,2)) resulting in rounding to 2 decimals. Is this really intenden?

Steps to reproduce

Create a model and corresponding database with float type on Value

public class Index
{
        public int Id { get; set; }
        public double Value { get; set; }
}

Call it as:

DbContext.Indexes.Select(t=> new{decimalValue = (decimal)t.Value}).First();

This will give you a decimal value with maximum 2 decimals.

Further technical details

EF Core version: 3.0, and 3.1 preview Database provider: Microsoft.EntityFrameworkCore.SqlServer Target framework: NET Core 3.0 Operating system: IDE: Visual Studio 2019 16.3

KaptenJon avatar Nov 05 '19 12:11 KaptenJon

@smitpatel I assume this is because we use the default type mapping for decimal?

ajcvickers avatar Nov 06 '19 19:11 ajcvickers

Yes, that is correct.

smitpatel avatar Nov 06 '19 19:11 smitpatel

@smitpatel Are there any cases when that default type mapping is actual relevant. Or is the solution to actually change that default mapping. I cannot come up with any cases.

KaptenJon avatar Nov 06 '19 21:11 KaptenJon

@KaptenJon The default type mapping is used because the use of decimal here is not associated with any decimal column in the database for which a different type mapping might be used. Implementation of #4978 would allow this to be changed.

ajcvickers avatar Nov 06 '19 21:11 ajcvickers

@ajcvickers I understnand, but shouldent the default sql decimal type be something that correspond with .net decimal type.

KaptenJon avatar Nov 07 '19 20:11 KaptenJon

@KaptenJon See #6965

ajcvickers avatar Nov 08 '19 15:11 ajcvickers

Note from triage: duplicate of #4978.

Workaround is to force the conversion on the client. For example:

var fromStore = DbContext.Indexes.Select(t=> new{ t.Value }).First();
var converted = new { value = (decimal)fromStore.Value };

ajcvickers avatar Nov 08 '19 20:11 ajcvickers