我正在试验这种代码优先的方法,但我现在发现类型System的属性。Decimal被映射到Decimal(18,0)类型的sql列。
如何设置数据库列的精度?
我正在试验这种代码优先的方法,但我现在发现类型System的属性。Decimal被映射到Decimal(18,0)类型的sql列。
如何设置数据库列的精度?
当前回答
[Column(TypeName = "decimal(18,2)")]
这将与EF Core代码首次迁移一起工作,如下所述。
其他回答
显然,你可以重写DbContext.OnModelCreating()方法,并像这样配置精度:
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>().Property(product => product.Price).Precision = 10;
modelBuilder.Entity<Product>().Property(product => product.Price).Scale = 2;
}
但当你必须处理所有与价格相关的属性时,这是相当乏味的代码,所以我想到了这个:
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
var properties = new[]
{
modelBuilder.Entity<Product>().Property(product => product.Price),
modelBuilder.Entity<Order>().Property(order => order.OrderTotal),
modelBuilder.Entity<OrderDetail>().Property(detail => detail.Total),
modelBuilder.Entity<Option>().Property(option => option.Price)
};
properties.ToList().ForEach(property =>
{
property.Precision = 10;
property.Scale = 2;
});
base.OnModelCreating(modelBuilder);
}
在重写方法时调用基方法是一种良好的实践,即使基实现什么也不做。
更新:这篇文章也很有帮助。
编辑,从。net 6开始,这可以用precision属性代替
(精密(精度、规模))
EF Core之前的版本:
[列(TypeName = "十进制(精度,比例)")]
定义:
精度=使用的字符总数
刻度=点后的总数。(容易混淆)
例子:
using System.ComponentModel.DataAnnotations; //.Net Core
using Microsoft.EntityFrameworkCore; //.NET 6+
public class Blog
{
public int BlogId { get; set; }
[Column(TypeName = "varchar(200)")]
public string Url { get; set; }
[Column(TypeName = "decimal(5, 2)")]
public decimal Rating { get; set; }
[Precision(28, 8)]
public decimal RatingV6 { get; set; }
}
更多详情请访问:https://learn.microsoft.com/en-us/ef/core/modeling/relational/data-types
您可以在实体数据模型的MSDN方面找到更多信息。 http://msdn.microsoft.com/en-us/library/ee382834.aspx 完整的建议。
实际的EntityFrameworkCore 3.1.3:
OnModelCreating中的一些解决方案:
var fixDecimalDatas = new List<Tuple<Type, Type, string>>();
foreach (var entityType in builder.Model.GetEntityTypes())
{
foreach (var property in entityType.GetProperties())
{
if (Type.GetTypeCode(property.ClrType) == TypeCode.Decimal)
{
fixDecimalDatas.Add(new Tuple<Type, Type, string>(entityType.ClrType, property.ClrType, property.GetColumnName()));
}
}
}
foreach (var item in fixDecimalDatas)
{
builder.Entity(item.Item1).Property(item.Item2, item.Item3).HasColumnType("decimal(18,4)");
}
//custom decimal nullable:
builder.Entity<SomePerfectEntity>().Property(x => x.IsBeautiful).HasColumnType("decimal(18,4)");
下面的代码行可以更简单地实现相同的目的:
public class ProductConfiguration : EntityTypeConfiguration<Product>
{
public ProductConfiguration()
{
this.Property(m => m.Price).HasPrecision(10, 2);
}
}