保存到数据库、C# 时丢失的小数精度.我正在使用实体框架

本文关键字:精度 框架 实体 小数 数据库 保存 | 更新日期: 2023-09-27 18:32:10

我的模型

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; }
}

问题出在纬度和经度上。它们在SQL Server DB中的格式是十进制(11,6)。因此,当我在创建自中给出值纬度 = 41.32056 和经度 = 19.805542 时,我调试并看到模型是否正确构建

[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();
    }
}

但存储在数据库中的值是纬度 = 41.320000 和经度 = 19.800000。它应该是纬度 = 41.32056 和经度 = 19.805542。我错过了什么。

我的 DbContext 类看起来像这样

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; }      
    }

我从未使用过 DbModelBuilder。我是否必须更改我的 DbContext 类?

保存到数据库、C# 时丢失的小数精度.我正在使用实体框架

更新关于您的更新 - 您需要将以下内容添加到您的 ApplicationDbContext 中:

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

看这里

EF 代码优先中的小数精度和小数位数

尝试添加映射:

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