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 方法中。
\nprotected 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可以使用 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 进行测试。
将以下内容添加到OnModelCreating
dbcontext 中的方法中:
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)