繁体   English   中英

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

[英]Adding an entity to database with a navigation property that already exists

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

var foo = new Foo 
{
    Id = 0,
    Name = "Foo",
    Bar = new Bar 
    {
        Id = 1,
        Name = "Bar"
    }
}

foo需要添加到数据库中。 Bar可能已经存在于数据库中,因此如果存在,则不应再次添加。 如果我刚收到的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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM