Entity Framework Core - 将小数精度和小数位数设置为所有小数属性 [英] Entity Framework Core - setting the decimal precision and scale to all decimal properties
问题描述
我想将所有小数属性的精度设置为 (18,6).在 EF6 中,这很容易:
I want to set the precision of all the decimal properties to (18,6). In EF6 this was quite easy:
modelBuilder.Properties<decimal>().Configure(x => x.HasPrecision(18, 6));
但我似乎在 EF Core 中找不到与此类似的任何内容.删除级联删除约定不像在 EF6 中那么简单,所以我找到了以下解决方法:
but I can't seem to find anything similar to this in EF Core. Removing the cascade delete convention wasn't as simple as in EF6 so I found the following workaround:
EF6:
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
EF 核心:
foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
relationship.DeleteBehavior = DeleteBehavior.Restrict;
在我阅读这个之后,我尝试了类似的方法:
and after I read this, I tried a similar approach:
foreach (var entityType in modelBuilder.Model.GetEntityTypes()
.SelectMany(x => x.GetProperties())
.Where(x => x.ClrType == typeof(decimal)))
{
// what to do here?
}
我想知道我是否在正确的轨道上以及如何继续,如果不是,我是否应该开始在所有 decimal
属性上添加数据注释.
I would like if I am on the right track and how to continue, or if not, should I start putting data annotations on all the decimal
properties.
推荐答案
你已经接近了.这是代码.
You got close. Here's the code.
foreach (var property in modelBuilder.Model.GetEntityTypes()
.SelectMany(t => t.GetProperties())
.Where(p => p.ClrType == typeof(decimal) || p.ClrType == typeof(decimal?)))
{
// EF Core 1 & 2
property.Relational().ColumnType = "decimal(18, 6)";
// EF Core 3
//property.SetColumnType("decimal(18, 6)");
// EF Core 5
//property.SetPrecision(18);
//property.SetScale(6);
}
这篇关于Entity Framework Core - 将小数精度和小数位数设置为所有小数属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!