Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
947 views
in Technique[技术] by (71.8m points)

mysql - How to use unsigned int / long types with Entity Framework?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Update Feb 2021

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


Older Entity Framework versions:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...