【发布时间】:2022-01-13 19:22:31
【问题描述】:
我编写了一个简单的递归函数来爬上具有 ID 和 PARENTID 的表的树。
但是当我这样做时,我得到了这个错误
System.InvalidOperationException:“无法跟踪实体类型“InternalOrg”的实例,因为已经在跟踪具有相同键值 {'Id'} 的另一个实例。附加现有实体时,请确保仅附加一个具有给定键值的实体实例。
是否有另一种方法可以做到这一点,或者可以在一个 LINQ 表达式中完成?
private InternalOrgDto GetInternalOrgDto(DepartmentChildDto dcDto)
{
if (dcDto.InternalOrgId != null)
{
InternalOrg io = _internalOrgRepo.Get(Convert.ToInt32(dcDto.InternalOrgId));
InternalOrgDto ioDto = new InternalOrgDto
{
Id = io.Id,
Abbreviation = io.Abbreviation,
Code = io.Code,
Description = io.Description
};
return ioDto;
}
else
{
//manually get parent department
Department parentDepartment = _departmentRepo.Get(Convert.ToInt32(dcDto.ParentDepartmentId));
DepartmentChildDto parentDepartmenDto = ObjectMapper.Map<DepartmentChildDto>(parentDepartment);
return GetInternalOrgDto(parentDepartmenDto);
}
}
【问题讨论】:
-
显示调用堆栈。 Bug 绝对不在这个函数中。这可能是由
Attach、Update、Add引起的。 -
递归调用 .get() 的底层函数是原因。下面的解决方案有效
标签: linq recursion entity-framework-core