让我解释整个背景:
我正在使用ASP.NET MVC 2,EF4(POCO)。
我尝试为我的应用程序执行通用存储库。
我在更新多对多关系时遇到问题。
我有一个与多个表相关的项目。在视图中,用户选择所需的类别,并将所选的ID仅发送给Controller。
然后,Controller查询Category Repository,将其添加到主项:
item.Categories.Add(CategoriesRepository.Single(id);
但是,当我去存储库并尝试像这样保存时:
Entities.ApplyCurrentValues(entity);
Context.SaveChanges();
但是,我的实体状态为已添加。
然后,我无法保存我的实体:(。
我该如何解决这个问题?
感谢您的回答。
我在View中有以下代码:
<%= Html.CheckBoxList("Categories", ((IEnumerable<Categories>)ViewData["Categories"]).ToDictionary(c => c.ID.ToString(), c => c.Name)
, Model.Categories.ToDictionary(c => c.ID.ToString(),c => c.Name )) %>
CheckBoxList是HTMLHelper。
我将ID作为值放在View中,因为我不知道其他放置方式,然后从View中获取此信息。
如何使用ObjectStateManager.ChangeRelationshipState
方法?
喜欢这个? :
itemRepository.Db.ObjectStateManager.ChangeRelationshipState(item, item.Categories, "Categories", System.Data.EntityState.Modified);
我尝试这种方式,但它返回错误。
帮助!洛尔
答案 0 :(得分:2)
你遇到了一些问题。
1)ApplyCurrentValues
仅适用于标量属性。由于您尝试在Category
上的Categories
导航属性中添加Item
,因此无效。
2)你这样说:
用户选择所需的类别,并将所选的ID仅发送给Controller。
你的Controller如何接受一堆id?这个模型绑定是如何完成的?我们需要有关View如何绑定到模型的更多信息,以及传递给action方法的内容。但听起来你需要在ViewModel的帮助下重新设计这个特定的视图。
3)在MVC中使用POCO进行的更改跟踪是一个巨大的痛苦。在您的方案中,您需要使用 ObjectStateManager.ChangeRelationshipState手动将Categories
关系设置为**修改。
将它放在下巴上 - 首先抓住实体并使用Controller.UpdateModel
:
[HttpPost]
public ActionResult Item(Item item)
{
// get the existing item
var existingItem = ItemRepository.Single(item.Id);
// use MVC to update the model, including navigational properties
UpdateModel(existingItem);
// save changes.
Context.SaveChanges();
}