使用已存在的导航属性将实体添加到数据库

时间:2013-10-21 14:55:45

标签: c# entity-framework

我有以下对象被发送到服务器,并且请求被发送到数据库:

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) }

我尝试了以下代码段,但它们不起作用:

{{1}}

我错过了什么吗?我觉得做这样的事情应该不会很难。

1 个答案:

答案 0 :(得分:2)

你的第二部分几乎是正确的,你实际上并没有更新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);