EF Decimal小数保留问题

本文介绍了如何在EF ORM框架中处理Decimal类型的精度问题。默认情况下,Decimal类型保留两位小数并采用四舍五入。文章提供了两种解决方案:一是通过重写数据库上下文的OnModelCreating方法,二是使用自定义Attribute类并应用到属性标签上进行设置。

EF Decimal类型

EF ORM框架的Decimal类型默认是保留两位小数(四舍五入)

如果需要进行精度的修改,则进行如下修改。

方式一:
在数据库上下文的类中进行重写OnModelCreating方法

namespace ****
{
	 public class DbServiceContext : System.Data.Entity.DbContext
	 {
		//********Models
		//数据库实体Model
		public virtual DbSet<Product> products{ get; set; }
		protected override void OnModelCreating(DbModelBuilder modelBuilder)
		{         
			//Product表的Price字段精度精确到5位(decimal(18,5))
		  modelBuilder.Entity<Product>().Property(x => x.Price).HasPrecision(18, 5);
		}
	}
}

方式二:
添加如下Attribute类,使用Attribute属性标签进行设置

using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration.Configuration;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NetCare.TS.Comm.AttributeExtent
{
    [AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
    public class DecimalPrecisionAttribute : Attribute
    {
        private byte _precision = 18;
        private byte _scale = 5;

        public byte Precision { get { return this._precision; } set { this._precision = value; } }
        public byte Scale { get { return this._scale; } set { this._scale = value; } }

        public DecimalPrecisionAttribute(byte precision = 18, byte scale = 5)
        {
            Precision = precision;
            Scale = scale;
        }
    }

    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 bttween 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);
        }
    }
}

定义完成后,修改方式一种的OnModelCreating重写方法

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Add(new DecimalPrecisionAttributeConvention());
            base.OnModelCreating(modelBuilder);
        }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值