0

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

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

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

4

1 回答 1

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);
于 2013-10-21T15:05:10.340 回答