【问题标题】:Store float value with Entity Framework throws exception使用实体框架存储浮点值引发异常
【发布时间】:2020-04-28 20:41:57
【问题描述】:

我正在尝试使用 .Net Core API 和 Entity Framework 存储 gps 值、经度和纬度。

这是表格,有一些记录:

这是模型

public class Destinos
{
        [Key]
        public int idDestino { get; set; }
        public String nombreDestino { get; set; }
        public String direccionDestino { get; set; }
        public float longitudDestino { get; set; }
        public float latitudDestino { get; set; }
        public String referenciaDestino { get; set; }
}

运行此代码时:

[HttpGet]
public IEnumerable<Destinos> GettDestinos()
{
      return _context.tDestinos;
}

我得到了这个异常

你们有什么线索或解决方法吗?

【问题讨论】:

  • 因为您在数据库中允许空值,请尝试在您的 Destinos 类中将浮点数设为 float?double?
  • 我刚刚尝试过 double 并且它有效!非常感谢!

标签: sql-server visual-studio entity-framework asp.net-core


【解决方案1】:

在 C# 中,float 是 32 位单精度浮点数,是 System.Single 的同义词。在 SQL Server 中,floatfloat(53) 64 位双精度浮点数的同义词。

C# float = SQL Server 的 real 又名 float(24)

C# double = SQL Server 的 float

因此,SQL Server 可为空的浮点数的正确映射是 Nullable&lt;System.Double&gt; aka double?

public class Destinos
{
        [Key]
        public int idDestino { get; set; }
        public String nombreDestino { get; set; }
        public String direccionDestino { get; set; }
        public double? longitudDestino { get; set; }
        public double? latitudDestino { get; set; }
        public String referenciaDestino { get; set; }
}

【讨论】:

    猜你喜欢
    • 2011-10-03
    • 2016-06-18
    • 2018-09-13
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 2016-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多