The "uint" and "ulong" types in Entity Framework
In Entity Framework, class attributes using long data type can be The mapping is correct when adding a new migration (code-first), but the EF provider for mysql skips the ulong data type. How do I map a property to mysql's unsigned bigint?
Updated (February 2021)
Apparently EF Core now supports ulongs - see @JimbobTheSailor's answer below.
Older Entity Framework versions:
It turns out that Entity Framework does not support unsigned data types. For uint columns, the value can be stored in a larger signed data type (i.e. long). What about ulong columns? The generic solution doesn't work for me because it doesn't have a signed data type supported by EF that is large enough to hold a ulong without overflowing.
After thinking for a while, I found a simple solution for this problem: just store the data in a supported long type and convert it to a ulong when accessed. You might be thinking: "Wait, the maximum value of a ulong > the maximum value of a long!" You can still store the bytes of the ulong in a long and then reconvert it to a ulong when needed, because both There are 8 bytes. This will allow you to save ulong variables to the database via EF.
<code class="csharp">// 避免直接修改以下内容。 // 仅用作数据库列。 public long __MyVariable { get; set; } // 访问/修改此变量。 // 告诉 EF 不要将此字段映射到数据库表 [NotMapped] public ulong MyVariable { get { unchecked { return (ulong)__MyVariable; } } set { unchecked { __MyVariable = (long)value; } } }</code>
Will prevent overflow exceptions if conversion is not checked.
Hope this helps.
The above is the detailed content of How to Map `ulong` Properties to Unsigned BigInts in MySQL with Entity Framework?. For more information, please follow other related articles on the PHP Chinese website!