![](/img/trans.png)
[英]The instance of entity type 'Entity' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked
[英]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.