EF Code First 中的小数精度和小数位数
我正在尝试这种代码优先的方法,但我现在发现 System.Decimal 类型的属性被映射到 Decimal(18, 0) 类型的 sql 列。
如何设置数据库列的精度?
I'm experimenting with this code-first approach, but I'm find out now that a property of type System.Decimal gets mapped to a sql column of type decimal(18, 0).
How do I set the precision of the database column?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(20)
戴夫·范·登·艾德 (Dave Van den Eynde) 的答案现已过时。有 2 个重要更改,从 EF 4.1 开始,ModelBuilder 类现在为 DbModelBuilder 现在有一个 DecimalPropertyConfiguration.HasPrecision 方法,其签名为:
其中 precision 是数据库将存储的总位数,无论小数点所在的位置和比例是它将存储的小数位数。
因此,不需要迭代所示的属性,但可以从
The answer from Dave Van den Eynde is now out of date. There are 2 important changes, from EF 4.1 onwards the ModelBuilder class is now DbModelBuilder and there is now a DecimalPropertyConfiguration.HasPrecision Method which has a signature of:
where precision is the total number of digits the db will store, regardless of where the decimal point falls and scale is the number of decimal places it will store.
Therefore there is no need to iterate through properties as shown but the can just be called from
如果您想设置 EF6 中所有小数的精度,您可以替换
DbModelBuilder
中使用的默认DecimalPropertyConvention
约定:默认
EF6 中的 DecimalPropertyConvention
将decimal
属性映射到decimal(18,2)
列。如果您只希望单个属性具有指定的精度,那么您可以在
DbModelBuilder
上设置实体属性的精度:或者,为实体添加
EntityTypeConfiguration
其中指定精度:If you want to set the precision for all
decimals
in EF6 you could replace the defaultDecimalPropertyConvention
convention used in theDbModelBuilder
:The default
DecimalPropertyConvention
in EF6 mapsdecimal
properties todecimal(18,2)
columns.If you only want individual properties to have a specified precision then you can set the precision for the entity's property on the
DbModelBuilder
:Or, add an
EntityTypeConfiguration<>
for the entity which specifies the precision:我为此创建了一个自定义属性,度过了愉快的时光:
像这样使用它
,神奇的事情发生在模型创建时,并进行一些反射,
第一部分是获取模型中的所有类(我的自定义属性是在该程序集中定义的,所以我使用了为了获得模型的组件)
第二个 foreach 获取该类中具有自定义属性的所有属性以及属性本身,这样我就可以
在必须调用之后
获得精度和比例数据,所以我调用 modelBuilder.Entity()通过反射并将其存储在entityConfig变量中
然后我构建“c => c.PROPERTY_NAME”lambda表达式
之后,如果小数可为空,我调用该
方法(我通过数组中的位置来调用它,我知道这并不理想,任何帮助将不胜感激)
,如果它不可为空,我调用该
方法。
有了 DecimalPropertyConfiguration,我就调用 HasPrecision 方法。
I had a nice time creating an Custom Attribute for this:
using it like this
and the magic happens at model creation with some reflection
the first part is to get all classes in the model (my custom attribute is defined in that assembly so i used that to get the assembly with the model)
the second foreach gets all properties in that class with the custom attribute, and the attribute itself so i can get the precision and scale data
after that i have to call
so i call the modelBuilder.Entity() by reflection and store it in the entityConfig variable
then i build the "c => c.PROPERTY_NAME" lambda expression
After that, if the decimal is nullable i call the
method (i call this by the position in the array, it's not ideal i know, any help will be much appreciated)
and if it's not nullable i call the
method.
Having the DecimalPropertyConfiguration i call the HasPrecision method.
使用 KinSlayerUY 中的
DecimalPrecisonAttribute
,在 EF6 中,您可以创建一个约定来处理具有该属性的各个属性(而不是像 这个答案将影响所有小数属性)。然后在您的
DbContext
中:Using the
DecimalPrecisonAttribute
from KinSlayerUY, in EF6 you can create a convention which will handle individual properties which have the attribute (as opposed to setting theDecimalPropertyConvention
like in this answer which will affect all decimal properties).Then in your
DbContext
:这将与 EF Core 代码优先迁移一起使用,如所述 在这里。
this will work with EF Core code first migrations as described here.
显然,您可以重写 DbContext.OnModelCreating() 方法并像这样配置精度:
但是,当您必须对所有与价格相关的属性执行此操作时,这是非常乏味的代码,所以我想出了这个:
这是一个很好的做法当您重写方法时,您会调用基本方法,即使基本实现不执行任何操作。
更新:本文 也很有帮助。
Apparently, you can override the DbContext.OnModelCreating() method and configure the precision like this:
But this is pretty tedious code when you have to do it with all your price-related properties, so I came up with this:
It's good practice that you call the base method when you override a method, even though the base implementation does nothing.
Update: This article was also very helpful.
实体框架版本 6(Alpha、rc1)有一个称为自定义约定的东西。设置小数精度:
参考:
Entity Framework Ver 6 (Alpha, rc1) has something called Custom Conventions. To set decimal precision:
Reference:
从 .NET EF Core 6 开始,您可以使用 Precision 属性。
确保您需要安装 EF Core 6 并执行以下
using
行From .NET EF Core 6 onwards you can use the Precision attribute.
make sure that you need to install EF Core 6 and do following
using
line替换
编辑,从 .NET 6 开始,可以用精度属性
[Precision
( precision, scale)]以前版本的 EF Core:
[Column
(TypeName
= "decimal
( precision, scale)")]
定义:
精度 = 使用的字符总数
比例 > = 点后的总数。 (容易混淆)
示例:
更多详细信息请参见:https://learn.microsoft.com/en-us/ef/core/modeling/relational/data-types
Edit, From .NET 6, this can been replaced with precision attribute
[Precision
(precision, scale)]Previous version of EF Core:
[Column
(TypeName
= "decimal
(precision, scale)")]
Definitions:
Precision = Total number of characters used
Scale = Total number after the dot. (easy to get confused)
Example:
More details here: https://learn.microsoft.com/en-us/ef/core/modeling/relational/data-types
此代码行可能是完成相同任务的更简单方法:
this code line could be a simpler way to acomplish the same:
您始终可以通过 OnModelCreating 函数中 Context 类中的约定告诉 EF 执行此操作,如下所示:
这仅适用于 Code First EF fyi 并适用于映射到数据库的所有十进制类型。
You can always tell EF to do this with conventions in the Context class in the OnModelCreating function as follows:
This only applies to Code First EF fyi and applies to all decimal types mapped to the db.
在 EF6 中
In EF6
使用
您可以简单地将该属性放入您的模型中:
Using
You can simply put that attribute in your model :
这就是我一直在寻找的,适用于普通 MVC 项目(无 .Net Core)
包管理器控制台
生成的迁移
This is what I was looking for, works for ordinary MVC project (No .Net Core)
Package manager console
Generated migration
您可以在 MSDN - 实体数据模型方面找到更多信息。
http://msdn.microsoft.com/en-us/library/ee382834.aspx
满推荐。
You can found more information on MSDN - facet of Entity Data Model.
http://msdn.microsoft.com/en-us/library/ee382834.aspx
Full recommended.
EntityFrameworkCore 3.1.3 的实际情况:
OnModelCreating 中的一些解决方案:
Actual for EntityFrameworkCore 3.1.3:
some solution in OnModelCreating:
您可以使用列属性或精度属性简单地从模型设计类中设置小数精度和比例,如下所示:
you can simply set decimal pricision and scale from Model Design class by using Column Attribute or Precision Attribute like following :
KinSlayerUY 的自定义属性对我来说效果很好,但我在使用 ComplexTypes 时遇到了问题。它们被映射为属性代码中的实体,因此无法映射为 ComplexType。
因此,我扩展了代码以允许这样做:
KinSlayerUY's custom attribute worked nicely for me but I had issues with ComplexTypes. They were being mapped as entities in the attribute code so couldn't then be mapped as a ComplexType.
I therefore extended the code to allow for this:
@Mark007,我已经更改了类型选择标准以乘坐 DbSet<> DbContext 的属性。我认为这更安全,因为有时给定名称空间中的类不应该是模型定义的一部分,或者它们是但不是实体。或者您的实体可以驻留在单独的命名空间或单独的程序集中,并被拉到一个上下文中。
另外,尽管不太可能,但我认为依赖方法定义的顺序并不安全,因此最好通过参数列表将它们拉出来。 (.GetTypeMethods() 是我为使用新的 TypeInfo 范例而构建的扩展方法,并且可以在查找方法时扁平化类层次结构)。
请注意 OnModelCreating 委托给此方法:
@Mark007, I have changed the type selection criteria to ride of the DbSet<> properties of the DbContext. I think this is safer because there are times when you have classes in the given namespace that shouldn't be part of the model definition or they are but are not entities. Or your entities could reside in separate namespaces or separate assemblies and be pulled together into once Context.
Also, even though unlikely, I do not think it's safe to rely on ordering of method definitions, so it's better to pull them out with by Parameter list. (.GetTypeMethods() is an extension method I built to work with the new TypeInfo paradigm and can flatten class hierarchies when looking for methods).
Do note that OnModelCreating delegates to this method:
我也有同样的问题,但我太懒了,找不到解决方案。
我只是使用一直存在的 double 类型,并在图形用户界面中格式化十进制数字......
我只是想在这里提到这一点,因为有时你不会想出最简单的解决方案。
I had the same question, but I'm too lazy for the solutions.
I just use the type double that has been around forever and format the decimal digits in the graphical user interface....
I just wanted to mention this here because sometimes you don't come up with the simplest solutions.