我有以下对象被发送到服务器并请求添加到数据库:
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)
}
我错过了什么吗?我觉得做这样的事情应该不会很难。