var entitys= Repository.Table.Where(a => ids.Contains(a.UUID)).ToList(); entitys.ForEach(a => { //foreach (var deductionitem in a.Deductionitems){} //取出来就删除不了了
var items=a.Deductionitems
DoDelete(a);
});
DeductionItems和主表配了级联删除,代码执行时会抛The relationship could not be changed because one or more of the foreign-key properties is non-nullable
场景为:删除主表时,在其对应的子表集合中,从子表通过导航属性去更新另外一个表的某个合计字段
解决方法:
遍历子表后,EF无法分辨该记录是否要保留。所以需要手动删除从表,不能再依赖级联删除
附上主表实体部分字段
public class MaterialSupplierPayApply : BaseSupplierPayApply { public MaterialSupplierPayApply() { } public MaterialSupplierPayApply(Currency currency, decimal exchangeRate, MaterialSupplier supplier) : base(currency, exchangeRate, supplier) { } public override string SysBillTypeCode => FuncCodeConst.Scm.MATERIALSUPPLIERPAYAPPLY; private List<MaterialSupplierPayDeductionItem> _deductionItems; /// <summary> /// 应付扣款明细 /// </summary> public virtual List<MaterialSupplierPayDeductionItem> DeductionItems { get => _deductionItems ?? (_deductionItems = new List<MaterialSupplierPayDeductionItem>()); set => _deductionItems = value; } }
以下为子表实体
/// <summary> /// 应付扣款明细 /// </summary>
public class MaterialSupplierPayDeductionItem:BaseEntityLog
{ public MaterialSupplierPayDeductionItem() { } public MaterialSupplierPayDeductionItem(MaterialSupplierPayableDeduction materialSupplierPayableDeduction,Guid billId) { BillId = billId; materialSupplierPayableDeduction.WriteOffStatus = WriteOffStatus.WriteOffing; MaterialSupplierPayableDeduction = materialSupplierPayableDeduction; } /// <summary> /// 付款申请 /// </summary> public Guid BillId { get; set; } /// <summary> /// 材料商应付扣款Id /// </summary> public Guid MaterialSupplierPayableDeductionId { get; set; } /// <summary> /// 备注 /// </summary> public string Description { get; set; } #region 导航属性 /// <summary> /// 材料商付款申请 /// </summary> public virtual MaterialSupplierPayApply MaterialSupplierPayApply { get; set; } /// <summary> /// 材料商应付扣款 /// </summary> public virtual MaterialSupplierPayableDeduction MaterialSupplierPayableDeduction { get; set; } #endregion }