efcore mysql codefirst设置decimal 默认精度和自定义精度
efcore mysql codefirst decimal 精度控制
·
项目原使用的是oracle的mysql库,在使用codefirst的时候有时候会出现列名不能修改,外键不能正常删除的情况,后在网上查询后决定使用pomelo.mysql库。原来decimal默认精度为(18,2)这个用起来刚刚好,但是一直不能自定义,换成pomelo后,出现默认值直接变成30多位小数,没办法只能查资料,最终找到方法通过自定义属性进行精度的控制。并且当不设置自定义属性时,默认值还是(18,2)。网上资料比较分散并且不完全正确,所以再归纳一下,本环境是efcore5,项目是.net5
主要步骤如下:
1、定义一个DecimalPrecisionAttribute类。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model
{
[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public class DecimalPrecisionAttribute : Attribute
{
#region Field
private byte _precision = 18;
public byte _scale = 2;
#endregion
#region Construct
/// <summary>
/// <para>自定义Decimal类型的精确度属性</para>
/// </summary>
/// <param name="precision">precision
/// <para>精度(默认18)</para></param>
/// <param name="scale">scale
/// <para>小数位数(默认2)</para></param>
public DecimalPrecisionAttribute(byte precision = 18, byte scale = 2)
{
Precision = precision;
Scale = scale;
}
#endregion
#region Property
/// <summary>
/// 精确度(默认18)
/// </summary>
public byte Precision
{
get { return this._precision; }
set { this._precision = value; }
}
/// <summary>
/// 保留位数(默认2)
/// </summary>
public byte Scale
{
get { return this._scale; }
set { this._scale = value; }
}
#endregion
}
}
2、在DbContext重写OnModelCreating方法。
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
#region 此处设置decimal默认精度为18,2如果有自定义注释,则直接使用自定义注释
foreach (var property in modelBuilder.Model.GetEntityTypes()
.SelectMany(t => t.GetProperties())
.Where(p => p.ClrType == typeof(decimal) || p.ClrType == typeof(decimal?)))
{
var precis = property.PropertyInfo.GetCustomAttribute<DecimalPrecisionAttribute>();
if (precis == null)
{
property.SetPrecision(18);
property.SetScale(2);
}
else
{
property.SetPrecision(precis.Precision);
property.SetScale(precis.Scale);
}
}
#endregion
base.OnModelCreating(modelBuilder);
}
如果代码跑不起来,或者无效,可能是环境问题,可以留言。
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)