.Net Entity Framework Core 用 HasColumnType 配置浮点数精度

时间:2023-03-09 19:58:40
.Net Entity Framework Core 用 HasColumnType 配置浮点数精度

一、前言

前段时间用.Net Entity Framework core搭建框架,需要配置浮点数的精度,发现.Net Entity Framework core 并没有HasPrecision方法。在网上查找资料也比较少,最后通过官方文档说明,尝试使用HasColumnType配置浮点数精度成功。

二、HasColumnType官方文档说明

文档连接:

https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.entityframeworkcore.relationalpropertybuilderextensions.hascolumntype?view=efcore-2.0#Microsoft_EntityFrameworkCore_RelationalPropertyBuilderExtensions_HasColumnType_Microsoft_EntityFrameworkCore_Metadata_Builders_PropertyBuilder_System_String_

.Net Entity Framework Core 用 HasColumnType 配置浮点数精度

 三、对比.Net Entity Framework 和.Net Entity Framework Core 配置

.Net Entity Framework方法:

public class MyProjectContext : DbContext
{
public DbSet<Order> Orders { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
//配置订单的金额浮点数精度为decimal(18,6)
modelBuilder.Entity<Order>().Property(t => t.Amount).HasPrecision(, );
    }
}

.Net Entity Framework Core方法:

public class MyProjectContext : DbContext
{
public DbSet<Order> Orders { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Order>(b =>
{
          //配置订单的金额浮点数精度为decimal(18,6)
b.Property(p => p.Amount).HasColumnType("decimal(18,6)");
});
     }
}