یک نکتهی تکمیلی: چگونه دقت خواصی از نوع decimal را به صورت سراسری تنظیم کنیم؟
فرض کنید قصد دارید دقت خواصی از نوع decimal را تنظیم کنید تا با اخطار زیر مواجه نشوید:
No type was specified for the decimal column 'Price' on entity type 'Movie'.
This will cause values to be silently truncated if they do not fit in the default precision and scale.
یک روش رفع آن، قرار دادن ویژگی Column بر روی تک تک خواص از نوع decimal، در تمام موجودیتهای تعریف شده و تنظیم دقت آنها است:
public class Movie
{
public int ID { get; set; }
[Column(TypeName = "decimal(18, 2)")]
public decimal Price { get; set; }
}
روش دیگر، انجام این تنظیم به صورت سراسری است:
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
foreach (var property in builder.Model.GetEntityTypes()
.SelectMany(t => t.GetProperties())
.Where(p => p.ClrType == typeof(decimal)
|| p.ClrType == typeof(decimal?)))
{
property.SetColumnType("decimal(18, 6)");
}
}
که هر دو نوع خاصیت decimal و ?decimal را پوشش میدهد.