Decimal precision is lost when stored in DB, C #. I am using Entity Framework

My model

public class Hotel { public int Id { get; set; } [Required] [Display(Name="Hotel Name")] public string HotelName {get;set;} [Required] public string Address { get; set; } [Required] [DisplayFormat(DataFormatString = "{0:N6}", ApplyFormatInEditMode = true)] [RegularExpression(@"\d{1,10}(\.\d{1,6})", ErrorMessage = "Invalid Latitude")] public Decimal Latitude { get; set; } [Required] [DisplayFormat(DataFormatString = "{0:N6}", ApplyFormatInEditMode = true)] [RegularExpression(@"\d{1,10}(\.\d{1,6})", ErrorMessage = "Invalid Longitude")] public Decimal Longitude { get; set; } [Required] [RegularExpression(@"\d{10,20}", ErrorMessage = "Invalid Number")] public string Telephone { get; set; } [Required] [EmailAddress] public string Email { get; set; } } 

The problem is latitude and longitude. Their format in SQL Server DB is decimal (11, 6). Therefore, when I give the values ​​Latitude = 41.32056 and Longitude = 19.805542 in create from, I debug and see that the model is built correctly

 [HttpPost] public ActionResult Create(Hotel hotel) { try { // TODO: Add insert logic here if (ModelState.IsValid) { db.Hotels.Add(hotel); db.SaveChanges(); } return RedirectToAction("Index"); } catch { return View(); } } 

but the value stored in the database is Latitude = 41.320000 and Longitude = 19.800000. It should be Latitude = 41.32056 and Longitude = 19.805542. What am I missing.

The My DbContext class is as follows

 public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } public DbSet<Hotel> Hotels { get; set; } public DbSet<Notification> Notifications { get; set; } public DbSet<Room> Rooms { get; set; } public DbSet<Booking> Bookings { get; set; } public DbSet<Audit> Audit { get; set; } } 

I have never used DbModelBuilder. Do I need to change the DbContext class?

+5
source share
2 answers

UPDATE Regarding your update, you need to add the following to ApplicationDbContext :

  protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Hotel>().Property(x => x.Longitude).HasPrecision(11, 6); } 

Look at here

Decimal precision and scale in the first EF code

+3
source

Try adding a display:

 modelBuilder.Entity<Hotel>().Property(x => x.Longitude).HasPrecision(11, 6); 
+4
source

Source: https://habr.com/ru/post/1241604/


All Articles