gpt4 book ai didi

c# - 添加属性以在 Entity Framework Core 中配置小数精度

转载 作者:行者123 更新时间:2023-12-02 01:31:08 60 4
gpt4 key购买 nike

我的 EF 6 .Net Framework 应用程序具有以下属性:

[AttributeUsage(AttributeTargets.Property)]          
public sealed class DecimalPrecisionAttribute : Attribute
{
public DecimalPrecisionAttribute(Byte precision, Byte scale)
{
Precision = precision;
Scale = scale;
}

public Byte Precision { get; set; }
public Byte Scale { get; set; }
}

public class DecimalPrecisionAttributeConvention
: PrimitivePropertyAttributeConfigurationConvention<DecimalPrecisionAttribute>
{
public override void Apply(
ConventionPrimitivePropertyConfiguration configuration,
DecimalPrecisionAttribute attribute)
{
if (attribute.Precision < 1 || attribute.Precision > 38)
{
throw new InvalidOperationException("Precision must be between 1 and 38.");
}

if (attribute.Scale > attribute.Precision)
{
throw new InvalidOperationException(
"Scale must be between 0 and the Precision value.");
}

configuration.HasPrecision(attribute.Precision, attribute.Scale);
}
}

然后在我的 DbContext 中:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Add(new DecimalPrecisionAttributeConvention());
base.OnModelCreating(modelBuilder);
}

这使我能够设置 POCO 上属性的精度:

[DecimalPrecision(5,2)]
public Decimal WeirdNumber { get; set; }

但我无法弄清楚如何为 EF Core 执行此操作。

.Core 中有等效的吗?

我得出以下结论:

public static class DecimalPrecisionAttributeConvention
{
public static void ApplyToTable(IMutableEntityType table)
{
foreach (var col in table.GetProperties())
{
var attribute = col
?.PropertyInfo
?.GetCustomAttributes<DecimalPrecisionAttribute>()
?.FirstOrDefault();

if (attribute == null)
{
continue;
}

if (attribute.Precision < 1 || attribute.Precision > 38)
{
throw new InvalidOperationException("Precision must be between 1 and 38.");
}

if (attribute.Scale > attribute.Precision)
{
throw new InvalidOperationException(
"Scale must be between 0 and the Precision value.");
}

col.Relational().ColumnType =
$"decimal({attribute.Precision}, {attribute.Scale})";
}
}
}

并在模型上创建瘦身:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
{
foreach (var table in modelBuilder.Model.GetEntityTypes())
{
DecimalPrecisionAttributeConvention.ApplyToTable(table);
}
}

这是实现这一目标的最佳方法吗?

最佳答案

对于 EntityFrameworkCore,我使用此解决方案。在 DbContext 中,重写 OnModelCreating 方法:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);

// Set default precision to decimal property
foreach (var property in modelBuilder.Model.GetEntityTypes()
.SelectMany(t => t.GetProperties())
.Where(p => p.ClrType == typeof(decimal) || p.ClrType == typeof(decimal?)))
{
property.SetColumnType("decimal(18, 2)");
}
}

希望这有帮助。

关于c# - 添加属性以在 Entity Framework Core 中配置小数精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46749041/

60 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com