Click here to Skip to main content
15,892,480 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
Hi,

Iam using entityframework in my project. I have a column called Factor in db and its datatype is decimal(16,5) nullable.

I gave input like 312.3132388888888888 and it is saving in db like 312.31000 not sure the reason. I have debugged the code and seen its getting full value, it is not rounding in code.

It looks like it is updating 2 decimals, but when manually update the value in sql database using update query it is updating correctly.

Can any one tell what is causing the issue, am I missing anything?


Thanks in Advance!!!

What I have tried:

I have found following solution but I have more than 20 decimal columns. Is there any other solution where I can apply all columns?

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Metrics>().Property(x => x.PPM).HasPrecision(4, 3);
    }
Posted
Updated 17-Dec-16 8:53am
v3

It is probably connected to the default values of a decimal in EF, which is (18,2)...
If you want something different you have to declare it, it is not enough that you have it in the DB...
So your solution is the best you may have...
 
Share this answer
 
Comments
NaVeN Kumar 18-Dec-16 10:35am    
Hi Kornfeld, I have verified and found some articles where they have created like below.. Is that correct way? will it causes any performance issue?

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class Precision : Attribute
{
public byte precision { get; set; }
public byte scale { get; set; }

public Precision(byte precision, byte scale)
{
this.precision = precision;
this.scale = scale;
}

public static void ConfigureModelBuilder(DbModelBuilder modelBuilder)
{
modelBuilder.Properties().Where(x => x.GetCustomAttributes(false).OfType(Precision).Any()).Configure(c => c.HasPrecision(c.ClrPropertyInfo.GetCustomAttributes(false).OfType(Precision).First().precision, c.ClrPropertyInfo.GetCustomAttributes(false).OfType(Precision).First().scale));
}
}

Then in your OnModelCreating simply add the following:


Precision.ConfigureModelBuilder(modelBuilder);

And in your Model simply add the Precision attribute to any decimal properties.


[Precision(18, 9)]
public decimal? Latitude { get; set; }

Kornfeld Eliyahu Peter 18-Dec-16 12:13pm    
It is a perfect solution, but you still have to add that attribute to all of your decimal values!
You're only solution is to declare this, as appropriate, for each column you have.

No, there is no way to apply it in a single statement. It has nothing to do with the database at all, but everything to do with your EF model.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900