Ash K
Ash K

Reputation: 3651

Set precision and scale while saving into Db using entity framework

This is what the JSON response is:

{
  "data": [
    {
      "someTicketNum": "123456",
      "someTemperature": 2,
      "somePercent": 2.025
    }
  ]
}

The table it needs to be saved to is modeled as:

public class TableName
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long TicketID { get; set; }
    public float? SomeTemperature { get; set; }
    public decimal? SomePercent { get; set; }
}

These Db columns are set up as: SomeTemperature(decimal(3,1), null) and SomePercent(decimal(7,5), null).

I want values for these properties to be saved as follows:

SomeTicketNum: "123456",
SomeTemperature: 2.0,  // The examples values are: 0.0, 1.5, 99.9 etc.
SomePercent: 2.02500 // The example values are: 0.00000, 1.50000, 99.99999 etc.

I've tried this in the model builder:

modelBuilder.Entity<TableName>().Property(x => x.SomeTemperature).HasPrecision(3,1);
modelBuilder.Entity<TableName>().Property(x => x.SomePercent).HasPrecision(7, 5);

Turns out .HasPrecision can only be set in decimal properties so I changed data type of SomeTemperature to decimal? which made the error go away that was originally saying:

'PrimitivePropertyConfiguration' does not contain a definition for 'HasPrecision' and no accessible extension method 'HasPrecision' accepting a first argument of type 'PrimitivePropertyConfiguration' could be found (are you missing a using directive or an assembly reference?)

I just cannot figure out this exception while trying to save this record to Db, which says:

Inner Ex. Msg: String or binary data would be truncated. The statement has been terminated.

I've aligned all the data type in db and c# model.

What am I doing wrong here? P.S. I'm using EF6.

Upvotes: 1

Views: 332

Answers (2)

Ash K
Ash K

Reputation: 3651

About the exception:

Inner Ex. Msg: String or binary data would be truncated. The statement has been terminated.

I was attempting to save some other field with hard coded value like this:

SomeOtherField = (decimal)0.00000

Floating point numbers cannot be saved to a decimal field (SomeOtherField is a decimal), so changing it to:

SomeOtherField = 0.00000m

did the trick!

Upvotes: 1

Guru Stron
Guru Stron

Reputation: 142008

Your approach with HasPrecision should work:

modelBuilder.Entity<TableName>().Property(x => x.SomeTemperature).HasPrecision(3,1);
modelBuilder.Entity<TableName>().Property(x => x.SomePercent).HasPrecision(7, 5);

The issues is that HasPrecision is defined only for decimal (and DateTime but it is not relevant here) properties, so you need to change SomeTemperature property type to decimal?.

Upvotes: 1

Related Questions