简体   繁体   English

插入实体不会更新键字段

[英]Inserting entity doesn't update Key field

I'm trying to insert a detached entity into database using GraphDiff. 我正在尝试使用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 : 我的addObject函数基本上是:

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). 当我尝试获取新添加的Foo的ID时出现问题,它仍然为空(0)。

Shouldn't EF update object to what it actually inserted in database ? EF是否不应该将对象更新为它实际插入数据库中的对象? Am i missing something ? 我想念什么吗?

Well I found out right before posting the question that UpdateGraph had a return type and that I did not use it.. 好吧,我在发布问题之前就发现UpdateGraph具有返回类型,但我没有使用它。

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 : 将我的AddObject更改为此解决了问题:

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

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

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