验证 30000 没有为小数列指定类型

Syd*_*dev 6 c# entity-framework ef-core-2.0

在不使用属性的情况下指定小数精度的最佳方法是什么。我只需要在我的 Data.Models 中将所有小数设置在一个位置。其繁琐的为每个小数指定属性。

public class Customer
{
    public int customerId{ get; set; }

    [Column(TypeName = "decimal(18,2)")]
    public decimal AvailableAmount{ get; set; }
}
Run Code Online (Sandbox Code Playgroud)

Big*_*oul 15

对于那些在 EntityFrameworkCore 6.0 上遇到同样问题的人,可以这样做:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    var decimalProps = modelBuilder.Model
    .GetEntityTypes()
    .SelectMany(t => t.GetProperties())
    .Where(p => (System.Nullable.GetUnderlyingType(p.ClrType) ?? p.ClrType) == typeof(decimal));

    foreach (var property in decimalProps)
    {
        property.SetPrecision(18);
        property.SetScale(2);
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 9

我使用 ASP.NET CORE 5 遇到了这个问题。我将以下代码添加到 DbContext 中的 OnModelcreating 方法中。

\n
protected override void OnModelCreating(ModelBuilder modelBuilder)// Cr\xc3\xa9e la migration\n    {\n        modelBuilder.Entity<MyEntity>().Property(p => p.Prix).HasColumnType("decimal(18,4)");\n\n    }\n
Run Code Online (Sandbox Code Playgroud)\n

一切都开始正常工作。

\n


Szi*_*rdD 9

可以使用 Precision 属性来代替在 C# 代码中对十进制数据库类型进行硬编码

这:

[Column(TypeName = "decimal(18,2)")]
public decimal Quantity { get; set; }
Run Code Online (Sandbox Code Playgroud)

可以这样定义:

[Precision(18, 2)]
public decimal Quantity { get; set; }
Run Code Online (Sandbox Code Playgroud)

使用 EF Core 6 进行测试。


vah*_*ari 7

将以下内容添加到OnModelCreatingdbcontext 中的方法中:

 protected override void OnModelCreating(ModelBuilder builder)
        {
          
            foreach (var property in builder.Model.GetEntityTypes()
                .SelectMany(t => t.GetProperties())
                .Where(p => p.ClrType == typeof(decimal) || p.ClrType == typeof(decimal?)))
            {
              
                property.Relational().ColumnType = "decimal(18,2)";

              
            }
        }
Run Code Online (Sandbox Code Playgroud)

  • “Relational()”从何而来? (5认同)
  • 您应该安装“Microsoft.EntityFrameworkCore.Relational”包 (3认同)
  • 如果您的任何小数列不是十进制(18,2),则此答案是错误的。谨慎行事... (2认同)