Florian F.
Florian F.

Reputation: 4700

Inserting entity doesn't update Key field

I'm trying to insert a detached entity into database using GraphDiff.

It goes something like :

public IHttpActionResult Post([FromBody] Foo foo) {
    var newFoo = fooBusiness.AddObject(foo);
    if (newFoo != null) {
        return CreatedAtRoute("GetOperation", new { id = newFoo.Id }, newFoo);
    }
    return Conflict();
}

And my addObject function basically is :

public Foo AddObject(Foo entity)
{
    UpdateGraph(entity);
    _context.SaveChanges();
    return entity;
}

public override void UpdateGraph(Foo entity)
{
    DataContext.UpdateGraph(entity, map => map
        .AssociatedCollection(e => e.Bars)
        .AssociatedEntity(e => e.Baz)
    );
}

Problem comes when I try to get the Id of newly added Foo, it remains empty (0).

Shouldn't EF update object to what it actually inserted in database ? Am i missing something ?

Upvotes: 2

Views: 319

Answers (1)

Florian F.
Florian F.

Reputation: 4700

Well I found out right before posting the question that UpdateGraph had a return type and that I did not use it..

If you don't use the returned entity, the entities states will be well updated but the entity tracking will totally fail.

Changing my AddObject to this solved the problem :

public Foo AddObject(Foo entity)
{
    entity = UpdateGraph(entity);
    _context.SaveChanges();
    return entity;
}

public override Foo UpdateGraph(Foo entity)
{
    return DataContext.UpdateGraph(entity, map => map
        .AssociatedCollection(e => e.Bars)
        .AssociatedEntity(e => e.Baz)
    );
}

Upvotes: 3

Related Questions