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();
posted @   试试手气  阅读(1273)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示