将实体添加到具有已存在的导航属性的数据库
本文关键字:存在 导航 属性 数据库 实体 添加 | 更新日期: 2023-09-27 18:36:11
我有以下对象,它被发送到服务器,并请求附加到数据库:
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)
}
我错过了什么吗? 我觉得做这样的事情应该不是很难。
你的第二部分几乎是对的,你实际上并没有更新foo.Bar
这就是为什么我认为它试图创建一个新的,请尝试
var bar = context.bars.FirstOrDefault(x => x.Id == Foo.Bar.Id);
if (bar != null)
{
bar.Name = foo.Bar.Name;
foo.Bar = bar;
}
context.Foo.add(foo);