Home > Database > Mysql Tutorial > body text

How to Map `ulong` Properties to Unsigned BigInts in MySQL with Entity Framework?

Mary-Kate Olsen
Release: 2024-11-03 04:09:02
Original
986 people have browsed it

How to Map `ulong` Properties to Unsigned BigInts in MySQL with Entity Framework?

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template