gpt4 book ai didi

c# - 如何释放被跟踪的实体?

转载 作者:行者123 更新时间:2023-12-03 18:40:51 24 4
gpt4 key购买 nike

希望以下代码片段足够清楚地解释问题。 _dbDbContext 的一个实例.

// this scenario is only for learning purpose
Author a = _db.Authors.Find(1831);
int id = a.AuthorId;
a = null;

Author stub = new Author { AuthorId = id };
_db.Remove(stub);
_db.SaveChanges();

上面的代码产生

'The instance of entity type 'Author' cannot be tracked because another instance with the same key value for {'AuthorId'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.'





如何免费 a从被跟踪?

最佳答案

有多种方法可以做到这一点,但我发现这是最简单的,因为您要尝试分离特定实体。

_db.Entry(a).State = EntityState.Detached

作为一个加号,它不需要更改任何其他代码,包括您获取实体本身的方式。

这一行使意图非常明确。它还允许以下内容:
  • 获取实体或实体列表
  • 做各类工作
  • 分离实体

  • 我不喜欢在 DbContext 上更改现有查询的想法当我想做的就是分离一些东西时。

    关于c# - 如何释放被跟踪的实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55269717/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com