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

921

被折叠的 条评论
为什么被折叠?



