当我尝试读取记录,然后在同一事务中删除这些记录时,我一直在与 EF 作斗争。我最初使用 EntityState.Deleted 方法,这会给出错误:
操作失败:无法更改关系,因为一个或多个外键属性不可为空。当关系发生更改时,相关的外键属性将设置为空值。如果外键不支持空值,则必须定义新关系,必须为外键属性分配另一个非空值,或者必须删除不相关的对象。
但如果我将其更改为如下所示,使用 .Remove(),那么一切都很好。
- 使用 .Remove() 与 .Deleted 的区别和最佳时机是什么?
- 我怎样才能使用 .Deleted 方法来完成这项工作?我尝试在我的存储库中创建一个新的上下文实例以进行读取,并创建另一个实例以进行删除,但随后出现与 IEntityTracker 无法跟踪多个实例相关的错误...我也尝试过。在初始读取中包含以加载依赖记录到 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 (AllocationNeed allocNeed in allocNeeds)
{
try
{
//NO WORK: context.Entry(allocNeed).State = System.Data.EntityState.Deleted;
context.AllocationNeeds.Attach(allocNeed);
context.AllocationNeeds.Remove(allocNeed); <-- Works
context.SaveChanges();
}
catch (Exception ex)
{
return ActionConfirmation<int>.CreateFailureConfirmation(ex.Message, allocNeed.Id);
}
}
Remove
还将删除子对象,但使用Deleted
将不会。你真的应该使用Remove
正是因为这个原因。如果你really想要使用Deleted
,您必须使外键可为空,但最终会得到孤立的记录(这是您一开始就不应该这样做的主要原因之一)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)