JHixson
JHixson

Reputation: 1532

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

I have the following object which was send to the server with a request to be aded to the database:

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

foo needs to be added to the database. Bar may already exist in the database, so if it does, it should not be added again. If the Bar that i just recieved is different from the one in the database, (ie Name is different) then the Database should be updated to reflect the new Bar

I have tried the following code snippets, and they do not work:

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

Am I missing something? I feel like doing something like this shouldn't be very hard.

Upvotes: 0

Views: 373

Answers (1)

James
James

Reputation: 82136

Your second part is nearly right, you aren't actually updating foo.Bar though which is why I assume it's attempting to create a new one, try

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

Upvotes: 2

Related Questions