The instance of entity type 'Item' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked

前端 未结 6 2213
日久生厌
日久生厌 2021-02-14 13:21

I am aware that such question has already been asked, but solution did not help me.

[Fact]
public async Task UpdateAsync()
{
    string newTitle = \"newTitle1\";         


        
6条回答
  •  名媛妹妹
    2021-02-14 14:00

    Alexandar's answer, which was to disable tracking completely, solved my issue, but I got worried since I didn't know what this would do to the rest of my application. So I went to the Microsoft docs and found this:

    You should not disable change tracking if you want to manipulate entity instances and persist those changes to the database using SaveChanges().

    This method sets the default behavior for all contexts created with these options, but you can override this behavior for a context instance using QueryTrackingBehavior or on individual queries using the AsNoTracking(IQueryable) and AsTracking(IQueryable) methods.

    So the solution for me was to disable tracking only when needed. So I solved my issue by using this in the other part of my code that retrieved the same entry from the database:

    var entry = await context
        .SomeDbTable
        .AsNoTracking() // this is what you're looking for
        .Find(id);
    

提交回复
热议问题