親にぶら下がっているネストされた EF オブジェクトがあります。1:nの関係がある
[親]-[子]
ネストされたオブジェクトの子は動的で、GUI を通じて更新されます。
データベースでの更新に問題があります。
エラー メッセージ: 同じキーを持つオブジェクトが ObjectStateManager に既に存在します。ObjectStateManager は、同じキーを持つ複数のオブジェクトを追跡できません。
これは質問です 2 番目のバージョンです。preExist判定のifブロックを修正しました
よろしくお願いいたします。
座っているアヒル
メインの更新
void MainUpdate
{
var context = new FamilyEntities();
parent = getParentFromGui();
parent.UpdateRelatedEntities(context);
context.dispose();
}
オブジェクトの親が Gui で更新されました
parent getParentFromGui()
{
parent myParent = parentBindingSource.DataSource as parent;
foreach(child c in childrenBindingSource)
{
myParent.children.Add(c);
}
return myParent
}
変更された UpdateRelatedEntities
public static void UpdateRelatedEntities(this parent entity, FamilyEntities context)
{
if (entity == null) return;
var res = context.parent.Where(x => x.uid_parent == entity.uid_parent);
var rec = res.FirstOrDefault();
context.parent.Attach(rec);
context.parent.ApplyCurrentValues(entity);
foreach (var c in entity.children)
{
bool preExist = context.children.FirstOrDefault(x => x.child_uid == c.child_uid);
if (preExist != null)
{
context.children.Attach(obj);
context.children.ApplyCurrentValues(c);
}
else
{
// This Part throw ERROR
context.children.AddObject(c);
}
}
context.SaveChanges();
}
私が間違っているのは何ですか?
Txたくさん!