EF core 6 中浮点类型的默认精度和小数位数是多少?

What are the default precision and scale for floating point types in EF core 6?

我收到以下警告:

No store type was specified for the decimal property 'PurchasePrice' on entity type 'ProductStatisticsKeylessEntity'. This will cause values to be silently truncated if they do not fit in the default precision and scale. Explicitly specify the SQL server column type that can accommodate all the values in 'OnModelCreating' using 'HasColumnType', specify precision and scale using 'HasPrecision', or configure a value converter using 'HasConversion'.

(强调我的)

我知道如何设置精度和比例,但我想知道 EF 默认值 - decimalfloat 或 [=12= 的默认精度和比例究竟是什么]?

也许默认值足够好,我可以将 precision/scale 设置为相同的值以隐藏错误。

我不知道有任何关于 C# decimal 到 SQL 服务器 decimal 的默认精度和比例映射的官方文档。最快的方法就是尝试。

source code(参见 _clrTypeMappings 字段的初始化)显示小数默认映射到 decimal(18,2),因为它们一直在 Entity Framework 中。

floatdouble 都只有精度(和指数,但没有标度),所以这个问题在这里并不适用。但是对于这些类型,它们映射到 SQL Serer 类型很重要,因为双方的定义不同,令人困惑。

如果我们让 EF 从这个 class...

生成一个 table
public class Num
{
    public int Id { get; set; }
    public decimal Dec { get; set; }
    public float Float { get; set; }
    public double Double { get; set; }
}

...我们得到这个:

CREATE TABLE [dbo].[Nums](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Dec] [decimal](18, 2) NOT NULL,
    [Float] [real] NOT NULL,
    [Double] [float] NOT NULL,
 CONSTRAINT [PK_Nums] PRIMARY KEY CLUSTERED ([Id]))

所以从 CLR 到 SQL 服务器类型的默认映射是:

  • decimaldecimal(18,2)
  • floatreal
  • doublefloat

请注意,对于 float (CLR) 这并不是真正的默认值,它是唯一有意义的映射。对于 double 它是默认值,因为 double 的精度可以通过映射指令降低,例如:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Num>().Property(e => e.Double).HasPrecision(24);
}

在这种情况下,Double 属性 将映射到 SQL 服务器中的 real,因为它具有 storage size of a real.

请看一下,这是 .NET 6 中的新变化。

https://docs.microsoft.com/en-us/ef/core/modeling/entity-properties?tabs=data-annotations%2Cwithout-nrt

The Data Annotation for configuring precision and scale was introduced in EF Core 6.0.

你可以这样设置:

[Precision(14, 2)]
public decimal Score { get; set; }