且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在实体框架中使用 unsigned int/long 类型?

更新时间:2023-11-10 10:06:46

2021 年 2 月更新

显然 EF Core 现在支持 ulong -- 请参阅下面@JimbobTheSailor 的回答.

Apparently EF Core now supports ulong -- see @JimbobTheSailor's answer below.

较旧的实体框架版本:

事实证明实体框架不支持 unsigned 数据类型.对于 uint 列,可以将值存储在具有更大范围的有符号数据类型中(即 long).ulong 列呢?通用解决方案对我不起作用,因为没有 EF 支持的签名数据类型可以保存 ulong 而不会溢出.

Turns out that Entity Framework does not support unsigned data types. For uint columns, one could just store the value in a signed data type with a larger range (that is, a long). What about ulong columns? The common solution couldn't work for me because there is no EF-supported signed data type that can hold a ulong without overflowing.

经过一番思考,我想出了一个简单的解决方案:只需将数据存储在支持的long类型中,并在访问时将其转换为ulong.您可能会想:等等,ulong 的最大值 >long 的最大值!"您仍然可以将 ulong 的字节存储在 long 中,然后在需要时将其转换回 ulong,因为两者都有 8 个字节.这将允许您通过 EF 将 ulong 变量保存到数据库中.

After a bit of thinking, I figured out a simple solution to this problem: just store the data in the supported long type and cast it to ulong when accessed. You might be thinking: "But wait, ulong's max value > long's max value!" You can still store the bytes of a ulong in a long and then cast it back to ulong when you need it, since both have 8 bytes. This will allow you to save a ulong variable to a database through EF.

// Avoid modifying the following directly.
// Used as a database column only.
public long __MyVariable { get; set; }

// Access/modify this variable instead.
// Tell EF not to map this field to a Db table
[NotMapped]
public ulong MyVariable
{
    get
    {
        unchecked
        {
            return (ulong)__MyVariable;
        }
    }

    set
    {
        unchecked
        {
            __MyVariable = (long)value;
        }
    }
}

强制转换是unchecked 以防止溢出异常.

The casting is unchecked to prevent overflow exceptions.

希望这对某人有所帮助.

Hope this helps someone.