【问题标题】:Decimal Trimmed after 2 digits added Zeros while store to SQL Server存储到 SQL Server 时,在 2 位数字添加零后修整十进制
【发布时间】:2022-01-04 14:29:48
【问题描述】:

我试图将纬度和经度存储到我的数据库中。

我的表中有这些列:

[Latitude]  NUMERIC(12, 8) NULL,
[Longitude] NUMERIC(12, 8) NULL,

在C#模型类中,我的属性是:

[Column(TypeName = "numeric")]
[Range(-9999.99999999, 9999.99999999)]
public decimal? Latitude { get; set; }

[Column(TypeName = "numeric")]
[Range(-9999.99999999, 9999.99999999)]
public decimal? Longitude { get; set; }

我想将这些 LatitudeLongitude 值存储到我的数据库表中。

我在这里做错了什么?请帮忙

decimal lats = decimal.Parse("56.12345678");
decimal longs = decimal.Parse("10.18732210");

context.test.Add(new test
        {
            Latitude = lats,
            Longitude = longs
        });
context.SaveChanges();

它将值存储在数据库表中,如下所示:

Latitude: 56.12000000  
Longitude : 10.18000000

我希望将相同的值存储在数据库中:

"56.12345678"     
"10.18732210"

【问题讨论】:

  • 尝试将精度添加到TypeName。例如numeric(12,8)
  • 我已经在这个列的 Sql 中有这个类型
  • 你在使用 EF Core 吗?
  • 您的 c# 还需要注意精度。您可以使用下面答案中提供的 Fluent API 方法,但是由于您已经在使用数据注释来提供类型,因此我将通过将精度添加到 TypeName 中来指定它。

标签: c# sql-server asp.net-mvc decimal


【解决方案1】:

您可能还需要像这样在 OnModelCreating 中指定它:

modelBuilder.Entity<Test>().Property(a => a.Latitude).HasPrecision(18, 9);
modelBuilder.Entity<Test>().Property(a => a.Longitude).HasPrecision(18, 9);

以防万一您需要更多高级功能并且正在使用 EF Core,请查看: https://docs.microsoft.com/en-us/ef/core/modeling/spatial

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-16
  • 1970-01-01
  • 2011-12-30
  • 2010-10-23
  • 1970-01-01
  • 1970-01-01
  • 2011-06-25
相关资源
最近更新 更多