c# - EF Core 已跟踪具有相同 id 的实体

标签 c# entity-framework .net-core entity-framework-core

我不知道如何消除该错误:

The instance of entity type 'Relation' cannot be tracked because another instance with the key value '{Id: 26}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.

我尝试将实体与上下文分离,但即使这样也无法阻止此错误的发生。有人可以指出我做错了什么吗?

服务:

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);

但是 Relation 实体上的所有属性都没有得到更新。

更新2

运行以下代码时

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

我可以看到旧关系已使用新值进行更新,但它们并未应用于数据库...这是为什么?

最佳答案

我多年来一直使用此代码而不是“更新”,所有内容总是正确更新,并且从未出现过任何错误。

尝试对 EF 使用通用代码从来都不是一个好主意。如果您想更新多个类,请尝试选择这种方式:

 var oldrelation = Context.Relations
.Include(i=> i.Person)
.Include(i=> i.Company)
...
.FirstOrDefault(i=> i.Id=entity.Id);

替换

 Context.Relations.Update(relation); 

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

关于c# - EF Core 已跟踪具有相同 id 的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66988585/

相关文章:

c# - 哪些算法用于搜索单词中的子词?

azure - 通过Proxy .net core连接Azure存储

azure - 除了使用登录卡之外,还有其他方法在机器人中登录用户吗?

c# - 显示文件的属性页并导航到选项卡

c# - 这个 "No object for moniker"是什么消息?

c# - 如何从 .mov 视频文件头(QuickTime 文件格式)中读取比特率信息?

.net - EF Core linq 和条件包含然后包含问题

sql-server - 将 GUID 连接到字符串 - Entity Framework 产生缓慢的查询

entity-framework - 由于一个或多个外键属性不可为空,因此无法更改该关系

c# - 我可以在 C# 中将 gRPC 和 webapi 应用程序组合到 .NET Core 3.0 中吗?