Why Does My Entity Framework Turn '2.87' into Just '2' (Decimal Field)

Why does my Entity Framework turn '2.87' into just '2' (decimal field)?

You need to set the scale on the decimal field. Change the Score field to be decimal(18,2)

See Decimal help File on MSDN

You can set the Scale in EF by first selecting the field, then in the properties window you will see a property for Scale (see image)

Sample Image

How can I make a c# decimal match a SQL decimal for EF change tracking?

You could implement a proxy-property which handles the conversion from code-precision to db-precision:

public class MoneyClass
{
[Column("Money")]
public decimal MyDbValue { get; set; } // You existing db-property

[NotMapped]
public decimal MyCodeValue // some property to access within you code
{
get
{
return this.MyDbValue;
}
set
{
decimal newDbValue = decimal.Round(value, 2);
if (this.MyDbValue != newDbValue)
{
Console.WriteLine("Change! Old: {0}, New: {1}, Input: {2}", this.MyDbValue, newDbValue, value);
this.MyDbValue = newDbValue;
}
}
}
}

static void Main(params string[] args)
{
MoneyClass dbObj = new MoneyClass()
{
MyCodeValue = 123.456M
};

Console.WriteLine(dbObj.MyDbValue);
dbObj.MyCodeValue = 123.457M; // won't change anything
Console.WriteLine(dbObj.MyDbValue);
dbObj.MyCodeValue = 123.454M; // will change because of 3rd decimal value 4
Console.WriteLine(dbObj.MyDbValue);
dbObj.MyCodeValue = 123.46M; // will change
Console.WriteLine(dbObj.MyDbValue);
}

Entity Framework Database First Decimal Precision

The process is not as clear as it could be, but you do it in the properties. See these 2 links:

Entityframework model first decimal precision

With picture:

Why does my Entity Framework turn '2.87' into just '2' (decimal field)?



Related Topics



Leave a reply



Submit