SqlSugar 实践笔记
使用 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();
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?