データベースに追加する要求とともにサーバーに送信された次のオブジェクトがあります。
var foo = new Foo
{
Id = 0,
Name = "Foo",
Bar = new Bar
{
Id = 1,
Name = "Bar"
}
}
foo
データベースに追加する必要があります。 Bar
すでにデータベースに存在している可能性があるため、存在する場合は再度追加しないでください。Bar
受け取ったものがデータベース内のものと異なる場合 (つまり、異なるName
場合)、新しいものを反映するようにデータベースを更新する必要があります。Bar
次のコード スニペットを試しましたが、機能しません。
void Insert (Foo foo)
{
var bar = context.bars.FirstOrDefault(x => x.Id == Foo.Bar.Id)
if (bar != null)
{
context.bars.attach(foo.Bar)
// doesn't work because the search
//I just preformed already bound an object
//with this ID to the context,
//and I can't attach another with the same ID.
//Should I somehow "detach" the bar
//that I got from the search result first?
}
context.Foo.add(foo)
}
void Insert (Foo foo)
{
var bar = context.bars.FirstOrDefault(x => x.Id == Foo.Bar.Id)
if (bar != null)
{
bar = foo.Bar
// successfully updates the object in the Database,
// But does not stop the insert below from
// trying to add it again, throwing a SQL Error
// for violating the PRIMARY KEY constraint.
}
context.Foo.add(foo)
}
何か不足していますか?このようなことをするのはそれほど難しいことではないと思います。