繁体   English   中英

"使用 AsNoTracking() 获取“无法跟踪实体类型的实例,因为已经在跟踪具有相同键值的另一个实例”"

[英]Getting 'The instance of entity type cannot be tracked because another instance with same key value for is already being tracked' with AsNoTracking()

我正在使用 Entity Framework Core 创建我的 Telegram 机器人。 我有这些模型:

public class User
{
    public int Id { get; set; }
    public long UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string UserName { get; set; }
    public ICollection<Chat> Chats { get; set;} = new List<Chat>();
    public ICollection<Team> CreatedTeams { get; set; } = new List<Team>();
    public ICollection<Team> Teams { get; set; } = new List<Team>();
}

public class Team
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int? ChatId { get; set; }
    public Chat Chat { get; set; }
    public int? CreatorId { get; set; }
    public User Creator { get; set; }
    public ICollection<User> Users { get; set; } = new List<User>();
}

您似乎没有完全理解AsNoTracking<\/code>的作用:它明确地将实体与数据库断开连接。 因此,如果您想Update<\/code>该实体,则不应首先断开它。

它是一个关系数据库。 如果要将现有user<\/code>添加到team<\/code> ,则需要跟踪现有对象。 否则数据库将尝试创建一个具有完全相同<\/em>值的新数据库,并且会发生冲突。

旁注:你为什么使用Include<\/code> ,而不是延迟加载? 我们在我的公司运行几个大型应用程序,几乎不必使用Include<\/code> 。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM