相关疑难解决方法(0)

EntityState.Deleted不起作用,Remove(entity)呢?

在尝试读取记录时,我一直在与EF斗争,然后在同一个事务中删除这些记录.我最初使用的是EntityState.Deleted方法,它会产生错误:

操作失败:无法更改关系,因为一个或多个外键属性不可为空.当对关系进行更改时,相关的外键属性将设置为空值.如果外键不支持空值,则必须定义新关系,必须为外键属性分配另一个非空值,或者必须删除不相关的对象.

但是,如果我将它改为我在下面,使用.Remove(),那么一切都很好.

  1. 有什么区别和最佳使用时间.Remove()vs .Deleted?
  2. 我怎么能使用.Deleted方法来完成这项工作?我已经尝试创建一个新的上下文实例到我的存储库读取和另一个删除,但后来得到的错误与IEntityTracker无法跟踪多个实例...我也试过.Include在初始读取时加载依赖记录进入EF所以它知道并删除它们.我也尝试过.先读取读取的记录.一切都无济于事.

这是有问题的方法.请注意,我确实有一个使用.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

5
推荐指数
1
解决办法
6911
查看次数