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();

浙公网安备 33010602011771号