提问者:小点点

ef core已跟踪具有相同id的实体


我想不出如何摆脱这个错误:

无法跟踪实体类型“Relations”的实例,因为已在跟踪键值为“{id:26}”的另一个实例。附加现有实体时,确保只附加一个具有给定键值的实体实例。

我尝试将实体从上下文中分离出来,但即使这样也不能阻止这个错误的发生。有人能给我指出我做错了什么吗?

服务

    private async Task<int> EditAsync(RelationModel model)
    {
        RelationEntity entity = _mapper.ToEntity(model);
        RelationEntity oldRelation = await _relationRepository.GetRelationAsync(entity.Id);
        _relationRepository.UpdateRelation(oldRelation, entity);
        await _relationRepository.SaveAsync();
        return entity.Id;
    }

存储库

    public void UpdateRelation(Relation oldRelation, Relation relation)
    {
        if (oldRelation != null)
        {
            // Detach
            Context.Entry(oldRelation).State = EntityState.Detached;

            // Delete childs
            if (oldRelation.Person != null && relation.Person == null)
            {
                Context.Persons.Remove(oldRelation.Person);
            }

            if (oldRelation.Customer != null && relation.Customer == null)
            {
                Context.Customers.Remove(oldRelation.Customer);
            }

            if (oldRelation.Supplier != null && relation.Supplier == null)
            {
                Context.Suppliers.Remove(oldRelation.Supplier);
            }

            if (oldRelation.Employee != null && relation.Employee == null)
            {
                Context.Employees.Remove(oldRelation.Employee);
            }

            // Update parent
            Context.Relations.Update(relation); // <-- error occurs
        }
    }

关系实体

public class Relation : BaseEntity<int>
{
    public string Code { get; set; }

    public int? PersonId { get; set; }
    public Person Person { get; set; }

    public int? CompanyId { get; set; }
    public Company Company { get; set; }

    public int? CustomerId { get; set; }
    public Customer Customer { get; set; }

    public int? SupplierId { get; set; }
    public Supplier Supplier { get; set; }

    public int? EmployeeId { get; set; }
    public Employee Employee { get; set; }

    public ICollection<RelationRelations> ParentRelations { get; set; }
    public ICollection<RelationRelations> ContactPersons { get; set; }
    public ICollection<RelationContactMethod> ContactMethods { get; set; }
    public ICollection<RelationAddress> Addresses { get; set; }
}

更新

我试着替换

Context.Relations.Update(relation); 

Context.Entry(oldRelation).CurrentValues.SetValues(relation);

但关系实体上的任何属性都不会更新。


共1个答案

匿名用户

我使用这个代码而不是“update”,很多年了,所有的东西都被正确地更新了,我从来没有出现过任何错误。

替换

 Context.Relations.Update(relation); 

Context.Entry(oldRelation).CurrentValues.SetValues(relation);