保存到DB,C#时,十进制精度丢失。我正在使用实体框架

时间:2016-01-27 12:08:04

标签: c# asp.net-mvc entity-framework linq

我的模特

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)。因此,当我在create from中给出值Latitude = 41.32056和Longitude = 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中的值是Latitude = 41.320000和Longitude = 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类?

2 个答案:

答案 0 :(得分:7)

<强>更新 关于您的更新 - 您需要将以下内容添加到 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

答案 1 :(得分:5)

尝试添加映射:

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