我正在使用存储过程在保留所有历史记录的数据库中执行插入和(逻辑)删除。不允许更新应用程序。
我尝试插入一条引用Place
记录的新AusSuburb
记录。在调用context.Add
方法之前,有一些设置处理。
(向右滚动以征求意见)
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create( Place place)
{
place.ID = Guid.NewGuid(); // necessary Logic
place.CoreCreatingTransIdent = DbFacade.gDbFacade.Transaction.TransIdent; // necessary Logic
place.CoreCreatingUserIdent = DbFacade.gDbFacade.Transaction.UserIdent; // necessary Logic
place.CoreName = "test"; // dummy value for testing
DbFacade.db.Places.Add(place); // add the place to context control
EntityState x = DbFacade.db.Entry(place).State; // get status of place after add
EntityState y = DbFacade.db.Entry(place.AusSuburb).State; // get status of suburb after add
DbFacade.db.SaveChanges(); // save changes - throws error
return RedirectToAction("Index");
}
执行后,x = Created
和y = Unchanged
,正如所料。
SaveChanges
抛出无法找到的错误并更新AusSuburb
实体的存储过程。这很奇怪,因为我不想在该表上进行更新。我在相关的表格上插入。
在正常的绝望中,我为AusSuburb
表提供了一个更新存储过程,它只记录其调用并且什么都不做。结果是错误消失了,但没有记录任何内容。
因此,似乎SaveChanges
正在检查相关表是否存在更新过程,但是没有调用它。
我现在可以通过为每个表创建一堆更新过程并配置它们来解决这个问题,但我觉得这可能是一个错误,我应该在某处报告。
有没有人遇到这个或类似的?
d
答案 0 :(得分:0)
我认为您遇到了因插入断开连接的对象图而导致的问题。
当您致电DbFacade.db.Places.Add(place)
时,整个图表都会被标记为已添加,因此我希望调试人员在调用Created
而不是{{1}后告诉您y是EntityState y = DbFacade.db.Entry(place.AusSuburb).State;
}
所以EF应该尝试插入Unchanged
对象...所以它应该寻找一个插入过程...所以这并没有真正回答为什么它正在寻找更新过程呢?
讨厌!你有插入程序吗?它是否会调用更新程序?
无论如何,请阅读此内容并查看是否有帮助:
Why does Entity Framework Reinsert Existing Objects into My Database?