惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
V2EX
量子位
博客园 - 司徒正美
IT之家
IT之家
V
Visual Studio Blog
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
Google DeepMind News
Google DeepMind News
Last Week in AI
Last Week in AI
Microsoft Security Blog
Microsoft Security Blog
T
Tailwind CSS Blog
aimingoo的专栏
aimingoo的专栏
GbyAI
GbyAI
Vercel News
Vercel News
B
Blog
大猫的无限游戏
大猫的无限游戏
D
DataBreaches.Net
小众软件
小众软件
罗磊的独立博客
博客园 - 叶小钗
雷峰网
雷峰网
Martin Fowler
Martin Fowler
Hugging Face - Blog
Hugging Face - Blog
WordPress大学
WordPress大学

博客园 - 试试手气

Web Worker 入门 若依Ruoyi分离版替换 MyBatis-Plus 若依前端菜单管理中路由地址、组件路径、权限字符的使用 Idea clone 项目推送到自有仓库 Spring Boot —— Spring Security Spring Boot —— 集成文档工具 Spring Boot —— Filter 过滤器 Spring Boot —— Cors 跨域 Spring Boot —— 集成 Druid Spring Boot —— 集成 MyBatis-Plus Spring Boot —— 集成 Springdoc Navicat 使用笔记 Datagrip连接SQLServer失败 Asp.net mvc 笔记 Asp.net Core 笔记 mybatis 笔记 SQLServer 笔记 Asp.net Core 全局异常处理 Asp.net Core 基于Cookie的身份认证
SqlSugar 实践笔记
试试手气 · 2023-03-21 · via 博客园 - 试试手气

使用 Insertable + ExecuteReturnSnowflakeIdAsync 为Id赋值时Id字段不能自增,SqlSugarException The entity sets the primary key and is long

解决方式一:实体定义时,主键不能为可空类型

// 正确
public class EntityExample{
   [SugarColumn(IsPrimaryKey = true, ColumnName = "Id", IsOnlyIgnoreUpdate = true)]
   public long Id {get; set;}
}

// 错误
public class EntityExample{
   [SugarColumn(IsPrimaryKey = true, ColumnName = "Id", IsOnlyIgnoreUpdate = true)]
   public long? Id {get; set;}
}

解决方式二:数据库为SqlServer2012,实体的Id字段标记IsPrimaryKey = true属性,新增时使用雪花算法创建Id并将其赋值给新增记录,此时数据表Id字段不能设置为自增,否则插入失败,报SqlException。因此,打算自己管理Id时就从数据表开始不让其自动分配。

public class EntityExample{
   [SugarColumn(IsPrimaryKey = true, ColumnName = "Id", IsOnlyIgnoreUpdate = true)]
   public long Id {get; set;}
}

long Id = await Db.Insertable<ThirdpartyUserInfoModel>(model)
                .ExecuteReturnSnowflakeIdAsync();