[英]Entity Framework inserting record with composite key not inserting second field
[英]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.