How to use unsigned int / long types with Entity Framework?(如何在实体框架中使用 unsigned int/long 类型?)
问题描述
具有 long
数据类型的类属性在添加新迁移(代码优先)时正确映射,但 ulong
数据类型被 mysql 的 EF 提供程序跳过.如何映射一个属性来使用mysql的unsigned bigint
?
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
?
推荐答案
2021 年 2 月更新
显然 EF Core 现在支持 ulong
-- 请参阅下面@JimbobTheSailor 的回答.
Apparently EF Core now supports ulong
-- see @JimbobTheSailor's answer below.
较旧的实体框架版本:
事实证明实体框架不支持 unsigned
数据类型.对于 uint
列,可以将值存储在具有更大范围的有符号数据类型中(即 long
).ulong
列呢?通用解决方案对我不起作用,因为没有 EF 支持的签名数据类型可以保存 ulong
而不会溢出.
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.
经过一番思考,我想出了一个简单的解决方案:只需将数据存储在支持的long
类型中,并在访问时将其转换为ulong
.您可能会想:等等,ulong 的最大值 >long 的最大值!"您仍然可以将 ulong 的字节存储在 long 中,然后在需要时将其转换回 ulong,因为两者都有 8 个字节.这将允许您通过 EF 将 ulong 变量保存到数据库中.
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;
}
}
}
强制转换是unchecked
以防止溢出异常.
The casting is unchecked
to prevent overflow exceptions.
希望这对某人有所帮助.
Hope this helps someone.
这篇关于如何在实体框架中使用 unsigned int/long 类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在实体框架中使用 unsigned int/long 类型?
基础教程推荐
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01