The instance of entity type 'XXX' cannot be tracked because another insta....
EF同時打開兩個實例,
public IActionResult Client(Client client)
{
var client_temp = _ConfigurationDbContext.Clients.Include(i => i.AllowedGrantTypes).Where(c => c.Id==client.Id).FirstOrDefault();
.....
}
看以上代碼,前臺模型綁定時提交了一個Client實例,我們又用代碼自己從數(shù)據(jù)庫中創(chuàng)建了一個實例client_temp ,這樣,EF就同時跟蹤維護著兩個一模一樣的實例,當(dāng)我們對Client進(jìn)行編輯后,再保存,EF就拋出異常:
System.InvalidOperationException:“The instance of entity type 'Client' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using
這時候,我們只需要改一下代碼,告訴EF,不要跟蹤我們自己創(chuàng)建的client_temp 即可,用以下寫法:
var client_temp = _ConfigurationDbContext.Clients.AsNoTracking().Include(i => i.AllowedGrantTypes).Where(c => c.Id==client.Id).FirstOrDefault();
//注意AsNoTracking()的用法,可以使EF框架只跟蹤一個實例,
然后再保存就不報錯了。
其實我們也可以用另一種方法去解決這個問題,前面的代碼創(chuàng)建了兩個數(shù)據(jù)庫實例,一個是前臺提交過來的,另一個是我們自己手動從數(shù)據(jù)庫中拉去的,我們對前臺提交過來的模型進(jìn)行修改的保存,對數(shù)據(jù)庫拉取的置之不理,就報了上面的錯誤,其實我們可以對數(shù)據(jù)庫中拉取的client_temp 進(jìn)行修改去保存,而對前臺提交過來,模型自動綁定的Client進(jìn)行丟棄,這樣就不會報上面的錯了。