gpt4 book ai didi

c# - 插入实体不更新关键字段

转载 作者:行者123 更新时间:2023-11-30 22:01:36 24 4
gpt4 key购买 nike

我正在尝试使用 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)
);
}

关于c# - 插入实体不更新关键字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27564073/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com