Inserting entity doesn't update Key field

c# entity-framework graphdiff

Question

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 ?

1
2
12/19/2014 10:29:05 AM

Accepted Answer

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)
    );
}
3
12/19/2014 10:29:05 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow