簡體   English   中英

驗證 30000 沒有為小數列指定類型

[英]Validation 30000 No Type Specified for the Decimal Column

在不使用屬性的情況下指定小數精度的最佳方法是什么。 我只需要將它設置在我的 Data.Models 中所有小數的一個位置。 為每個小數點指定屬性是很乏味的。

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

    [Column(TypeName = "decimal(18,2)")]
    public decimal AvailableAmount { get; set; }
}

將以下內容添加到 dbcontext 中的OnModelCreating方法:

 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)";

              
            }
        }

對於那些在 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);
    }
}

我使用 ASP.NET CORE 5 遇到了這個問題。我將以下代碼添加到 DbContext 中的 OnModelcreating 方法中。

protected override void OnModelCreating(ModelBuilder modelBuilder)// Crée la migration
    {
        modelBuilder.Entity<MyEntity>().Property(p => p.Prix).HasColumnType("decimal(18,4)");

    }

一切都開始正常工作。

可以使用Precision屬性,而不是在 C# 代碼中對十進制數據庫類型進行硬編碼。

這個:

[Column(TypeName = "decimal(18,2)")]
public decimal Quantity { get; set; }

可以這樣定義:

[Precision(18, 2)]
public decimal Quantity { get; set; }

使用 EF Core 6 測試。

    foreach (var entityType in modelBuilder.Model.GetEntityTypes())
            {
                var properties = entityType.ClrType.GetProperties().Where(p => p.PropertyType == typeof(decimal));
              

                foreach (var property in properties)
                {
                    modelBuilder.Entity(entityType.Name).Property(property.Name).HasColumnType("decimal(18,2)");}

http://jameschambers.com/2019/06/No-Type-Was-Specified-for-the-Decimal-Column/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM