2

我正在尝试使用 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 不应该将对象更新为它实际插入数据库的内容吗?我错过了什么吗?

4

1 回答 1

3

好吧,我在发布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)
    );
}
于 2014-12-19T10:29:05.313 回答