节能父实体模型时更新包含集合不会被保存在数据库? [英] Model updates to contained collection not saved in DB when saving parent entity?
问题描述
问题:在MVC3&放子模型集合;实体框架4.1被正确模型通过编辑操作更新,但该数值不会被保存在数据库中。
概述:
- 型号对象者包含对象CaseRef的
- 个人属性更新越来越保存在数据库上db.SaveChanges(),但内部集合CaseRef属性更新不被保存
- 所有值绑定/正确映射在HttpPost的ActionResult编辑的条目(),因此该模型被从表更新成功提交(编辑视图)
模型:
公共类Person
{
公众人物()
{
this.CaseRefs =新的HashSet< CaseRef>();
}
//< ...更多的属性在这里...>
公共字符串名称{;组; }
公众诠释用户ID {搞定;组} 公共虚拟的ICollection< CaseRef> CaseRefs {搞定;组; }
}公共类CaseRef
{
//< ...更多的属性在这里...>
公众诠释DescId {搞定;组; }
公共虚拟人人{搞定;组; }
}
控制器 - 编辑(邮政)
[HttpPost]
公众的ActionResult编辑(人P)
{
如果(ModelState.IsValid)
{
//注意:此时从编辑表单域的所有已保存到模型
//特别是内部CaseRefs收藏价值的更新。
db.Entry(p)的.STATE = EntityState.Modified; //这个更改保存到Person.Name但不能更改保存到更新
在CaseRefs集合//值
db.SaveChanges();
返回RedirectToAction(「指数」);
}
设置 db.Entry(P)= .STATE EntityState.Modified;
您只设置父实体要修改。要同时修改导航属性,你必须标记它们全部进行修改。
因此,像: p.CaseRefs.ForEach(C => db.Entry(C)= .STATE EntityState.Modified);
Issue: Child model collection in MVC3 & Entity Framework 4.1 is being updated properly in model via Edit action but the values are not being saved in DB.
Overview: - Model object Person contains object CaseRef's - Person property updates are getting saved in the DB on db.SaveChanges() but internal collection CaseRef property updates are not being saved - All values are bound/mapped correctly upon entry of HttpPost ActionResult Edit() so the model is being updated successfully from Form submit (Edit View).
Models:
public class Person
{
public Person()
{
this.CaseRefs = new HashSet<CaseRef>();
}
// <...more properties here...>
public string Name { get; set; }
public int UserId {get; set}
public virtual ICollection<CaseRef> CaseRefs { get; set; }
}
public class CaseRef
{
// <...more properties here...>
public int DescId { get; set; }
public virtual Person Person { get; set; }
}
Controller - Edit (Post)
[HttpPost]
public ActionResult Edit(Person p)
{
if (ModelState.IsValid)
{
// NOTE: At this point all fields from Edit form have been saved to the model
// specifically the internal CaseRefs Collection value updates.
db.Entry(p).State = EntityState.Modified;
// This is saving changes to Person.Name but not saving changes to the updated
// values in CaseRefs collection
db.SaveChanges();
return RedirectToAction("Index");
}
Setting db.Entry(p).State = EntityState.Modified;
you only set the parent entity to modified. To also modify the navigational properties you have to mark them all as modified.
So something like: p.CaseRefs.ForEach(c => db.Entry(c).State = EntityState.Modified);
这篇关于节能父实体模型时更新包含集合不会被保存在数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!