我已經這是向服務器發送一個請求以下對象進行交鋒到數據庫的導航屬性:添加到數據庫中的實體已存在
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)
}
我錯過了什麼嗎?我覺得做這樣的事情不應該很難。
這篇文章將對象圖可以幫助的陷阱http://msdn.microsoft.com/en-us/magazine/dn166926.aspx – Colin
投票合併斷開對象圖在這裏:https://entityframework.codeplex.com/discussions/432661 – Colin