繁体   English   中英

插入实体不会更新键字段

[英]Inserting entity doesn't update Key field

我正在尝试使用GraphDiff将分离的实体插入数据库。

它像这样:

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

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

当我尝试获取新添加的Foo的ID时出现问题,它仍然为空(0)。

EF是否不应该将对象更新为它实际插入数据库中的对象? 我想念什么吗?

好吧,我在发布问题之前就发现UpdateGraph具有返回类型,但我没有使用它。

如果您不使用返回的实体,则实体状态将得到很好的更新,但是实体跟踪将完全失败。

将我的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