0

我正在尝试转换从数据库查询接收到的字节。

EF Core 返回 nullable tinyintas byte?,我需要将其转换为decimal.

有没有办法OnModelCreating用模型构建器转换它DbContext

我对 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;
}
4

2 回答 2

3

I think you are getting a little confused by the types here. The DB returns a byte? for a tinyint because a tinyint has only 8 bits of data. But otherwise it is an integer. If you want to convert it to a decimal, you would use the same mechanism as you would to convert an int or a long to a decimal: cast it. You do not want to convert a byte array to a decimal as that will try to interpret the data in the array as a binary representation of a decimal (see my last paragraph). So this code should suffice to do the conversion.

decimal? d = newByte == null ? null : (decimal)newByte; 

See that such a conversion is possible here: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/numeric-conversions

Note the remarks section here that indicates we are dealing with a binary representation of the number, where care must be taken in dealing with endianness, etc.

https://docs.microsoft.com/en-us/dotnet/api/system.bitconverter?view=net-6.0#remarks

Basically, numbers larger than a byte are technically stored as an array of bytes (since all memory is byte addressable in x86) but the interpration of those bytes into a number depends on the type of the number. For floating point numbers especially the structure of data inside the byte array is complex, broken into fields that represent the base, exponent and sign. And those are not always interpreted in a straightforward way. If you just give a byte array with 27 as the first byte, you don't know where that ends up in the several fields that make up the binary representation of a double. It may well work, but probably not.

于 2022-01-05T15:00:42.103 回答
0

代替

byte[] bArray = new byte[1];

您可以使用

byte[] bArray = {(byte)newByte};
于 2022-01-05T14:51:08.780 回答