且构网

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

如何使用Entity Framework使用unsigned int / long类型?

更新时间:2023-11-10 10:24:34

事实证明,实体框架不支持 unsigned 数据类型。对于 uint 列,可以将值存储在范围较大的签名数据类型(即 long )。 ulong 列?常见的解决方案对我来说无法工作,因为没有EF支持的签名数据类型可以持有 ulong 而不会溢出。



经过一番思考,我想出了一个简单的解决方案:只需将数据存储在支持的 long 类型中,并将其转换为 ulong 。你可能会想:但等等,ulong的最大值> long的最大值!您仍然可以将ulong的字节存储在一个很长的位置,然后在需要时将其重新设置为ulong,因为它们都有8个字节。这将允许您通过EF将一个ulong变量保存到数据库。

  //避免直接修改以下内容。 
//仅用作数据库列。
public long __MyVariable {get;组; }

//访问/修改此变量。
//告诉EF不要将此字段映射到Db表
[NotMapped]
public ulong MyVariable
{
get
{
未选中
{
return(ulong)__ MyVariable;
}
}

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

投票是 unchecked 以防止溢出异常。



希望这有助于某人。


Class properties with the long data type are properly mapped when adding a new migration (code-first), but ulong data types are skipped by mysql's EF provider. How does one map a property to use mysql's unsigned bigint?

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.

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;
        }
    }
}

The casting is unchecked to prevent overflow exceptions.

Hope this helps someone.