If you're using Entity Framework you might have noticed that your decimal values are defaulting to 2 decimal places in your database when it's being built.
Sometimes you'll want to store more than 2 decimal places for things like GPS co-ordinates.
Let's assume that you have an entity class called Location which has the following structure:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Project.Entities
{
public class Location
{
[Key]
public int Id { get; set; }
[Required]
[MaxLength(100, ErrorMessage = "Must be less than 100 characters long")]
public string Name{ get; set; }
[Required]
[DisplayFormat(DataFormatString = "{0:#,##0.00000#}", ApplyFormatInEditMode = true)]
public decimal Latitude { get; set; }
[Required]
[DisplayFormat(DataFormatString = "{0:#,##0.00000#}", ApplyFormatInEditMode = true)]
public decimal Longitude { get; set; }
}
}
To make sure that Entity Framework stores the GPS with more than 2 decimal places add the following to your DataContext file:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity().Property(q => q.Latitude).HasPrecision(18, 5);
modelBuilder.Entity().Property(q => q.Longitude).HasPrecision(18, 5);
}
NOTE: for some reason my code editor is adding a 'project.entities.location' tag to the end of the last code snippet - ignore this. It's just this editor getting a bit confused.
Member discussion