2017-01-30 36 views
0

我有以下模式:錯誤更新實體時,EF代碼第一

Schema image

如何正確使用EF代碼第一種方法更新實體?當我試圖做到這一點的:

this._context.Entry(foundEntity).CurrentValues.SetValues(entity); 
this._context.Entry(foundEntity).State = EntityState.Modified; 

它拋出異常,並說:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Bets_dbo.Matches_MatchID". The conflict occurred in database "UltraPlay.Betting.Platform", table "dbo.Matches", column 'ID'. 
The statement has been terminated. 

是否有可能通過根對象和所有孩子的更新?如何正確地做到這一點乾淨和快速?

+0

你能展示你的實體嗎? –

+0

請分享你的代碼,並告訴你在哪裏得到錯誤 –

+0

我想,變量「實體」是分離的。這樣對嗎? – jannagy02

回答

0

如果你想要附加一個包含子元素的元素,你還需要所有的子元素,例如,

this._context.Entry(foundEntity).CurrentValues.SetValues(entity); 
this._context.Entry(foundEntity).State = EntityState.Modified; 

this._context.Entry(entity.ChildElement).State = EntityState.Modified; // <-- 

如果它已經存在。

否則,EF假定子元素是模型的新元素,並嘗試插入(再次)。