0

I have these two entities:

public class TblUser
{
    public long Userid { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string PasswordSalt { get; set; }
    public string FullName { get; set; }
    public virtual ICollection<TblNotify> TblNotifies { get; set; }
}

public partial class TblNotify
{
    public Guid NotifyId { get; set; }
    public string Message { get; set; }
    public virtual TblUser ApprovalUser { get; set; }
}

The table tblNotify has a foreign key Userid.

DbContext was initially built as singleton service.

I call an update method:

uow.GetRepository<tblNotify>().Update(item);

It almost always updates successfully, but rarely, I got this error:

The instance of entity type 'Tbluser' cannot be tracked because another instance with the same key value for {'Userid'} 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.

It's weird because I only update the tblNotify table. How could I investigate this error further?

Any help will be appreciated.

Progman
  • 16,827
  • 6
  • 33
  • 48
user3011414
  • 119
  • 1
  • 2
  • 10
  • Does this answer your question? [The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked](https://stackoverflow.com/questions/36856073/the-instance-of-entity-type-cannot-be-tracked-because-another-instance-of-this-t) – knoxgon Dec 28 '22 at 08:01
  • thank Wolf G for your support, but I don't know why I update this entity but impact to related-entity. – user3011414 Dec 28 '22 at 08:19
  • I think I see the problem. This will answer your question. (Hopefully). Please refer here. https://stackoverflow.com/a/48204159/4393935 – knoxgon Dec 28 '22 at 08:30
  • I would suggest to use this method [UpdateSafe](https://stackoverflow.com/a/71438914/10646316), which will do all needed preparation for update. Actually it searches for already loaded entities and updates them, otherwise attaches entity. – Svyatoslav Danyliv Dec 28 '22 at 09:22

0 Answers0