我正在试验这种代码优先的方法,但我现在发现类型System的属性。Decimal被映射到Decimal(18,0)类型的sql列。
如何设置数据库列的精度?
我正在试验这种代码优先的方法,但我现在发现类型System的属性。Decimal被映射到Decimal(18,0)类型的sql列。
如何设置数据库列的精度?
当前回答
这就是我正在寻找的,适用于普通的MVC项目(没有。net核心)
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<YOUR_CLASS_NAME>().Property(x => x.YOUR_DECIAML_PROP).HasPrecision(18, 6);
base.OnModelCreating(modelBuilder);
}
}
包管理器控制台
add-migration changeDecimalPrecision
生成的迁移
public override void Up()
{
AlterColumn("dbo.YOUR_CLASS_NAME", "YOUR_DECIAML_PROP", c => c.Decimal(nullable: false, precision: 18, scale: 6));
}
其他回答
下面的代码行可以更简单地实现相同的目的:
public class ProductConfiguration : EntityTypeConfiguration<Product>
{
public ProductConfiguration()
{
this.Property(m => m.Price).HasPrecision(10, 2);
}
}
在EF6
modelBuilder.Properties()
.Where(x => x.GetCustomAttributes(false).OfType<DecimalPrecisionAttribute>().Any())
.Configure(c => {
var attr = (DecimalPrecisionAttribute)c.ClrPropertyInfo.GetCustomAttributes(typeof (DecimalPrecisionAttribute), true).FirstOrDefault();
c.HasPrecision(attr.Precision, attr.Scale);
});
编辑,从。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
从。net EF Core 6开始,你可以使用Precision属性。
[Precision(18, 2)]
public decimal Price { get; set; }
请确保您需要安装EF Core 6,并使用line进行以下操作
using Microsoft.EntityFrameworkCore;
[Column(TypeName = "decimal(18,2)")]
这将与EF Core代码首次迁移一起工作,如下所述。