我正在尝试转换从数据库查询中接收的字节。
EF将可空的tinyint返回为byte?,我需要将它转换为decimal。
是否有任何方法将其转换为OnModelCreating与DbContext中的模型生成器
我不太熟悉EF核心。到目前为止,我只做到了这一点-在我已经在处理程序中获得了我的对象之后:
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;
}发布于 2022-01-05 15:00:42
我想你被这里的类型弄糊涂了。DB返回一个微小的byte?,因为tinyint只有8位数据。但否则它就是一个整数。如果您想将其转换为decimal,您将使用与将int或long转换为decimal:强制转换相同的机制。您不希望将字节数组转换为decimal,因为这将尝试将数组中的数据解释为十进制的二进制表示(请参阅我的最后一段)。因此,这段代码应该足以完成转换。
decimal? d = newByte == null ? null : (decimal)newByte; 在这里确保这样的转换是可能的:https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/numeric-conversions
请注意这里的备注部分,它表明我们正在处理数字的二进制表示,在处理endianness时必须小心,等等。
https://learn.microsoft.com/en-us/dotnet/api/system.bitconverter?view=net-6.0#remarks
基本上,大于字节的数字在技术上是作为字节数组存储的(因为所有内存都是可以在x86中寻址的字节),但是这些字节之间的相互作用取决于数字的类型。对于浮点数,特别是字节数组中的数据结构是复杂的,分为表示基、指数和符号的字段。而这些并不总是以直截了当的方式来解释。如果您只是给出一个以27作为第一个字节的字节数组,那么您就不知道它在构成双二进制表示的几个字段中的位置。这很有可能奏效,但很可能行不通。
发布于 2022-01-05 14:51:08
而不是
byte[] bArray = new byte[1];您可以使用
byte[] bArray = {(byte)newByte};https://stackoverflow.com/questions/70594803
复制相似问题