gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:55:18 25 4
gpt4 key购买 nike

我收到以下警告:

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?

也许默认值已经足够好了,我可以将精度/比例设置为相同的值以隐藏错误。

最佳答案

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

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

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

如果我们让 EF 从这个类中生成一个表...

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 Server 类型的默认映射是:

  • 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 Server 中的 real,因为它具有 storage size of a real .

关于entity-framework-core - EF core 6 中浮点类型的默认精度和小数位数是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70288710/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com