我正在尝试使用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不应该将对象更新到它实际插入数据库中的内容吗?我错过了什么吗?
答案 0 :(得分: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)
);
}