【问题标题】:Decimal Precision Lost when saved to DB, C#. I am using Entity Framework [duplicate]保存到 DB、C# 时会丢失十进制精度。我正在使用实体框架 [重复]
【发布时间】:2016-05-04 09:08:34
【问题描述】:

我的模型

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

但存储在 DB 中的值是纬度 = 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# asp.net-mvc entity-framework linq


【解决方案1】:

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

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

看这里

Decimal precision and scale in EF Code First

【讨论】:

  • 这不应该是一个答案,而是一个重复的问题标志。
  • 非常感谢。将其添加到我的 ApplicationDbContext 后,我​​使用 Update-Database -Force 命令从包管理器控制台进行了迁移。再次感谢。
【解决方案2】:

尝试添加映射:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-02
    • 2012-12-28
    • 1970-01-01
    • 2013-07-21
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    相关资源
    最近更新 更多