The instance of entity type 'XXX' cannot be tracked because another insta....
EF同時(shí)打開兩個(gè)實(shí)例,
public IActionResult Client(Client client)
{
var client_temp = _ConfigurationDbContext.Clients.Include(i => i.AllowedGrantTypes).Where(c => c.Id==client.Id).FirstOrDefault();
.....
}
看以上代碼,前臺(tái)模型綁定時(shí)提交了一個(gè)Client實(shí)例,我們又用代碼自己從數(shù)據(jù)庫中創(chuàng)建了一個(gè)實(shí)例client_temp ,這樣,EF就同時(shí)跟蹤維護(hù)著兩個(gè)一模一樣的實(shí)例,當(dāng)我們對(duì)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
這時(shí)候,我們只需要改一下代碼,告訴EF,不要跟蹤我們自己創(chuàng)建的client_temp 即可,用以下寫法:
var client_temp = _ConfigurationDbContext.Clients.AsNoTracking().Include(i => i.AllowedGrantTypes).Where(c => c.Id==client.Id).FirstOrDefault();
//注意AsNoTracking()的用法,可以使EF框架只跟蹤一個(gè)實(shí)例,
然后再保存就不報(bào)錯(cuò)了。
其實(shí)我們也可以用另一種方法去解決這個(gè)問題,前面的代碼創(chuàng)建了兩個(gè)數(shù)據(jù)庫實(shí)例,一個(gè)是前臺(tái)提交過來的,另一個(gè)是我們自己手動(dòng)從數(shù)據(jù)庫中拉去的,我們對(duì)前臺(tái)提交過來的模型進(jìn)行修改的保存,對(duì)數(shù)據(jù)庫拉取的置之不理,就報(bào)了上面的錯(cuò)誤,其實(shí)我們可以對(duì)數(shù)據(jù)庫中拉取的client_temp 進(jìn)行修改去保存,而對(duì)前臺(tái)提交過來,模型自動(dòng)綁定的Client進(jìn)行丟棄,這樣就不會(huì)報(bào)上面的錯(cuò)了。