连表更新问题 返回

SqlSugar 沟通中
3 566
public async Task BlockedByWarehouse(IEnumerable<WarehouseStock> _needlist, bool allowNegative = false)
{
	var needlist = _needlist.ToList();
	if (needlist.Any(x => x.Quantity <= 0))
		throw new Exception("占用数量必须大于0");
	var query = sugarScope.Reportable(needlist.Select(i => new { i.WarehouseId, i.GoodsId, i.Quantity, BlockedQuantity = 0 }).ToList()).ToQueryable();
	var rows = await sugarScope.Updateable<WarehouseStock>()
		.InnerJoin(query, (l, r) => l.WarehouseId == r.WarehouseId && l.GoodsId == r.GoodsId)
		.SetColumns((l, r) => new WarehouseStock { BlockedQuantity = l.BlockedQuantity - r.Quantity })
		.Where((l, r) => l.Quantity >= l.BlockedQuantity + r.Quantity)
		.ExecuteCommandAsync();
	if (rows != needlist.Count())
		throw new Exception("仓库库存占用失败");
}
public class WarehouseStock : BaseEntity
{
	/// <summary>
	/// 仓库编号
	/// </summary>
	[SugarColumn(IsPrimaryKey = true)]
	public long WarehouseId { get; set; }
	/// <summary>
	/// 货品id
	/// </summary>
	[SugarColumn(IsPrimaryKey = true)]
	public long GoodsId { get; set; }
	/// <summary>
	/// 数量
	/// </summary>
	public decimal Quantity { get; set; }
	/// <summary>
	/// 冻结数量
	/// </summary>
	public decimal BlockedQuantity { get; set; }

	[Navigate(NavigateType.OneToOne, nameof(WarehouseId))]
	public Warehouse? Warehouse { get; set; }

	[Navigate(NavigateType.OneToOne, nameof(GoodsId))]
	public Goods? Goods { get; set; }
}
[Tenant(DataDB.主库)]
/// <summary>
/// 实体基类
/// </summary>
public class BaseEntity : IDeleted, ITable
{
	/// <summary>
	/// 逻辑删除标记
	/// </summary>
	public long IsDeleted { get; set; } = 0;
	/// <summary>
	/// 创建时间
	/// </summary>
	[SugarColumn(InsertServerTime = true, IsOnlyIgnoreUpdate = true)]
	public DateTime CreateTime { get; set; }
	/// <summary>
	/// 更新时间
	/// </summary>
	[SugarColumn(InsertServerTime = true, UpdateServerTime = true)]
	public DateTime ModifyTime { get; set; }
	/// <summary>
	/// 版本标识(乐观锁)
	/// </summary>
	[SugarColumn(IsEnableUpdateVersionValidation = true)]
	public long Ver { get; set; }
}
var list = new List<WarehouseStock> { new() {WarehouseId =1,GoodsId=122,Quantity=5}}
await stockService.BlockedByWarehouse(model.Items!.GroupBy(i => i.GoodsId)!.Select(i => new WarehouseStock
{
	WarehouseId = model.SourceWarehouseId!.Value,
	GoodsId = i.Key!.Value,
	Quantity = i.Sum(_ => _.TransferQuantity!.Value)
}));

执行到 

ar rows = await sugarScope.Updateable<WarehouseStock>()
		.InnerJoin(

这里是 报错  "Sequence contains no elements"
将 

.SetColumns((l, r) => new WarehouseStock { BlockedQuantity = l.BlockedQuantity - r.Quantity })

屏蔽后 发现生成的语句 除了set 部分 其他都是正确的

热忱回答3

  • fate sta fate sta VIP0
    2025/11/27

    什么库

    0 回复
  • @fate sta:SqlSugarCore 5.1.4.207

    0 回复
  • @fate sta:如果 屏蔽掉 BaseEntity 的 

    [SugarColumn(InsertServerTime = true, UpdateServerTime = true)]
        public DateTime ModifyTime { getset; }

    就没问题了 应该是  UpdateServerTime = true 引起的

    0 回复