EF用導航屬性遍歷從表時,刪除主表出錯
- 2020 年 5 月 27 日
- 筆記
var entitys= Repository.Table.Where(a => ids.Contains(a.UUID)).ToList(); entitys.ForEach(a => { foreach (var deductionitem in a.Deductionitems){} DoDelete(a); }
DeductionItems和主表配了級聯刪除,程式碼執行時會拋The relationship could not be changed because one or more of the foreign-key properties is non-nullable
解決方法:
遍歷子表後,EF無法分辨該記錄是否要保留。所以需要手動刪除從表,不能再依賴級聯刪除