c# - 设置查询结果对象的小数精度

标签 c# entity-framework-core entity-framework-core-2.1

我有一个通过 Nuget 提供给我的类(class)。我没有消息来源。

 public class SpecialProductResult
  {
    public int id { get; set; }
    public decimal SpecialPercent {get;set;}
  }

我想从存储过程中填充 SpecialProductResult 列表

所以在我的 DbContext 我有
public DbQuery<SpecialProductDto> SpecialProducts { get; set; }

我使用填充列表
var specialProducts =   connect.SpecialProducts.FromSql("spGetSpecialProducts").ToList()

在错误日志中,我看到类似的消息

No type was specified for the decimal column ‘“SpecialPercent”’ on entity type ‘“SpecialProductResult”’. This will cause values to be silently truncated if they do not fit in the default precision and scale. Explicitly specify the SQL server column type that can accommodate all the values using ‘ForHasColumnType()’.



我看了this question并想尝试
modelBuilder.Entity<SpecialProductResult>().Property(o => o.GoldPercent).HasPrecision(18,4)

但是没有属性 .HasPrecision

我应该尝试什么?

[更新]

我尝试了 Ivan Stoev 的回答,但收到了运行时错误
The entity type 'SpecialProductResult' cannot be added to the model because a query type with the same name already exists

最佳答案

目前 EF Core 不提供指定数字类型精度和小数位数的数据库独立方式(类似于 EF6 HasPrecision)。

唯一的方法是使用 HasColumnType并指定数据库特定类型。如果需要支持不同的数据库,必须使用if声明和不同 HasColumnType对于每种数据库类型。

对于 SqlServer,它将是

modelBuilder.Query<SpecialProductResult>()
    .Property(o => o.GoldPercent)
    .HasColumnType("decimal(18,4)");

关于c# - 设置查询结果对象的小数精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57933402/

相关文章:

entity-framework - 循环/反射(reflect)所有 EF 模型中的所有属性以设置列类型

.net - EF Core linq 和条件包含然后包含问题

.net-core - Scaffold-DbContext(EF Core 工具)抛出 'Instance failure' 异常

c# - 访问参数的属性时使用 ArgumentNullException

c# - Blazor Dialog EventCallback 在没有参数的情况下工作,但编译器会抛出带参数的 CS1950

c# - 改进 Linq-XML 到对象查询

c# - 将员工分成每周轮类(4 周),每周唯一

c# - 从 ef core 的子集合中删除一些项目

c# - EF Core Group By 翻译支持条件总和

c# - 对 ITVF 的引用引发 "second operation started on this context before a previous operation completed"异常