【发布时间】:2022-01-05 14:43:49
【问题描述】:
我正在尝试转换从数据库查询接收到的字节。
EF Core 将可空的 tinyint 返回为 byte?,我需要将其转换为 decimal。
有什么方法可以用DbContext中的模型生成器将它转换为OnModelCreating?
我对 EF Core 不是很熟悉。到目前为止,我只设法做到了这一点 - 在我已经将我的对象放入处理程序之后:
decimal? newDecimal = Convert.ToDecimal(BitConverter.ToDouble(AddByteToArray(priceByte), 0)));
private static byte[] AddByteToArray(byte? newByte)
{
if (newByte != null)
{
if(newByte == 0)
{
return Enumerable.Repeat((byte)0x0, 8).ToArray();
}
byte[] bArray = new byte[1];
// Not sure how to convert a non null and byte > 0 to byte[]?? As double requires byte[] while the tinyint return byte from the database
return bArray;
}
return null;
}
【问题讨论】:
-
我不得不说我对答案不明显感到震惊。你没有转换任何东西。只需将那个字节放入数组中!
-
我刚开始尝试
Convert.ToDecimal,但没有成功。 -
这可能是因为该方法采用常规字节而不是可为空的字节。但是您可以通过在调用之前检查 null 然后转换为不可为空的字节来解决这个问题。这提醒您应该花时间了解类型在 C# 中的工作方式。听起来你只是在尝试一些事情,并希望有些事情能奏效。这是一种令人沮丧的编程方式
-
我比较了解类型。我以前从未真正使用过字节。
-
我在 db 上下文中尝试了 Convert.toDecimal() onmodelcreating 所以它更棘手。我之前也尝试过
modelBuilder .Entity<MyObject>() .Property(e => e.Price) .HasConversion( v => v != null ? (decimal)v : null;,但没有成功,是的,这可能让我更加困惑。
标签: c# arrays entity-framework-core byte tinyint