[英]Set decimal precision for query result object
I have a class supplied to me via Nuget.我有一个通过 Nuget 提供给我的课程。 I don't have the source.
我没有消息来源。
public class SpecialProductResult
{
public int id { get; set; }
public decimal SpecialPercent {get;set;}
}
I want to populate a list of SpecialProductResult from a stored procedure我想从存储过程中填充 SpecialProductResult 列表
So in my DbContext I have所以在我的 DbContext 我有
public DbQuery<SpecialProductDto> SpecialProducts { get; set; }
I populate the list using我使用填充列表
var specialProducts = connect.SpecialProducts.FromSql("spGetSpecialProducts").ToList()
In the error log I see messages like在错误日志中,我看到类似的消息
No type was specified for the decimal column '“SpecialPercent”' on entity type '“SpecialProductResult”'.
未为实体类型“SpecialProductResult”上的十进制列“SpecialPercent”指定类型。 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()'.
使用“ForHasColumnType()”显式指定可以容纳所有值的 SQL 服务器列类型。
I looked at this question and wanted to try我看着这个问题,想试试
modelBuilder.Entity<SpecialProductResult>().Property(o => o.GoldPercent).HasPrecision(18,4)
But there is no property .HasPrecision但是没有属性 .HasPrecision
What should I try?我应该尝试什么?
[Update] [更新]
I tried Ivan Stoev's answer but received a runtime error我尝试了 Ivan Stoev 的回答,但收到了运行时错误
The entity type 'SpecialProductResult' cannot be added to the model because a query type with the same name already exists
Currently EF Core does not provide database independent way of specifying the numeric type precision and scale (similar to EF6 HasPrecision
).目前 EF Core 不提供指定数字类型精度和小数位数的独立于数据库的方式(类似于
HasPrecision
)。
The only way to do that is to use HasColumnType and specify the database specific type.唯一的方法是使用HasColumnType并指定数据库特定类型。 If you need to support different databases, you have to use
if
statements and different HasColumnType
for each database type.如果您需要支持不同的数据库,则必须使用
if
语句,并为每种数据库类型使用不同的HasColumnType
。
For SqlServer, it would be对于 SqlServer,它将是
modelBuilder.Query<SpecialProductResult>()
.Property(o => o.GoldPercent)
.HasColumnType("decimal(18,4)");
Since EF Core 2.0 there is IEntityTypeConfiguration.从 EF Core 2.0 开始,有 IEntityTypeConfiguration。 In case you are using that approach, you can solve it as follows:
如果您正在使用该方法,则可以按如下方式解决:
class PartConfiguration : IEntityTypeConfiguration<Part>
{
public void Configure(EntityTypeBuilder<Part> builder){
builder.Property(c => c.PartId);
builder.Property(c => c.Number);
builder.Property(c => c.Size)
.HasPrecision(18, 4) <-- Use Either This
.HasColumnType("decimal(18,4)"); <-- Or this
}
}
...
// OnModelCreating
builder.ApplyConfiguration(new PartConfiguration());
For more information about using the ModelBuilder please refer to Microsoft Docs有关使用模型构建器的更多信息,请参阅Microsoft Docs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.