EF通过导航属性取出从表的集合后,无法删除子表
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 _deductionItems;
///
/// 应付扣款明细
///
public virtual List DeductionItems
{
get => _deductionItems ?? (_deductionItems = new List());
set => _deductionItems = value;
}
}
以下为子表实体
////// 应付扣款明细 ///
public class MaterialSupplierPayDeductionItem:BaseEntityLog
{
public MaterialSupplierPayDeductionItem() { }
public MaterialSupplierPayDeductionItem(MaterialSupplierPayableDeduction materialSupplierPayableDeduction,Guid billId)
{
BillId = billId;
materialSupplierPayableDeduction.WriteOffStatus = WriteOffStatus.WriteOffing;
MaterialSupplierPayableDeduction = materialSupplierPayableDeduction;
}
///
/// 付款申请
///
public Guid BillId { get; set; }
///
/// 材料商应付扣款Id
///
public Guid MaterialSupplierPayableDeductionId { get; set; }
///
/// 备注
///
public string Description { get; set; }
#region 导航属性
///
/// 材料商付款申请
///
public virtual MaterialSupplierPayApply MaterialSupplierPayApply { get; set; }
///
/// 材料商应付扣款
///
public virtual MaterialSupplierPayableDeduction MaterialSupplierPayableDeduction { get; set; }
#endregion
}