插入实体不会更新键字段
本文关键字:字段 更新 实体 插入 | 更新日期: 2023-09-27 18:34:45
我正在尝试使用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)
);
}