如何使用Entity Framework使用unsigned int / long类型? [英] How to use unsigned int / long types with Entity Framework?

查看:158
本文介绍了如何使用Entity Framework使用unsigned int / long类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当添加新的迁移(代码优先)但 ulong long 数据类型的类属性已正确映射c>数据类型被mysql的EF提供程序跳过。如何映射一个属性来使用mysql的 unsigned bigint

解决方案

事实证明,实体框架不支持 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.

这篇关于如何使用Entity Framework使用unsigned int / long类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆