在尝试读取记录时,我一直在与EF斗争,然后在同一个事务中删除这些记录.我最初使用的是EntityState.Deleted方法,它会产生错误:
操作失败:无法更改关系,因为一个或多个外键属性不可为空.当对关系进行更改时,相关的外键属性将设置为空值.如果外键不支持空值,则必须定义新关系,必须为外键属性分配另一个非空值,或者必须删除不相关的对象.
但是,如果我将它改为我在下面,使用.Remove(),那么一切都很好.
这是有问题的方法.请注意,我确实有一个使用.Deleted方法的通用存储库,该方法在此方案之前一直很好用(读取然后删除相同的记录.)
//Delete Allocation Need and AllocatedContainers for alloc need id
public ActionConfirmation<int> DeleteAllocRecords(int intFacilityId, AllocNeedSourceTypes needSourceType, int intNeedSourceId)
{
var context = new InventoryMgmtContext();
var repository = new AllocationNeedRepository(context);
//Delete Allocation Need and hence children in Allocated Containers
var srcType = needSourceType.ToString();
List<AllocationNeed> allocNeeds = repository.SearchFor(
x => x.FacilityId == intFacilityId
&& x.NeedSourceType == srcType
&& x.NeedSourceId == intNeedSourceId
).ToList();
//var deleteRepository = new Repository<AllocationNeed>(); <--tried separate instance of context to delete...no worky.
foreach …Run Code Online (Sandbox Code Playgroud) .net c# entity-framework exception-handling entity-framework-5