2017-01-30 127 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假定子元素是模型的新元素,并尝试插入(再次)。