当前位置: 代码迷 >> .NET Framework >> MVC3 更新关联数据有关问题
  详细解决方案

MVC3 更新关联数据有关问题

热度:21   发布时间:2016-05-02 00:13:36.0
MVC3 更新关联数据问题
Model中:
C# code
[Table("CompanyInfo")]    public class CompanyInfo    {        [Key]        public int id { get; set; }        [Required(AllowEmptyStrings=false, ErrorMessage="请输入单位名称")]        public string CompanyName { get; set; }        [Required(AllowEmptyStrings=false, ErrorMessage="请选择省份")]        public string ProvinceId { get; set; }        [Required(AllowEmptyStrings = false, ErrorMessage = "请选择城市")]        public string CityId { get; set; }        public List<AccountInfo> AccountInfos{ get; set; }        public List<DepartmentId> DepartmentIds { get; set; }    }

C# code
[Table("AccountInfo")]    public class AccountInfo    {        [Key]        public int id { get; set; }        [Column("CompanyId")]        public int CompanyInfoId { get; set; }        public string AccountName { get; set; }        public string TaxNumber { get; set; }        public string Address { get; set; }        public string Telephone { get; set; }        public string Account { get; set; }        public string Bank { get; set; }    }

C# code
[Table("DepartmentId")]    public class DepartmentId    {        [Key]        public int id { get; set; }        [Column("CompanyId")]        public int CompanyInfoId { get; set; }        [Required(AllowEmptyStrings=false, ErrorMessage="请输入下属部门名称")]        public string DepartmentName { get; set; }    }


在对CompanyInfo对象进行“update”操作的时候,
自身的属性字段是可以编辑并更新成功的,但是对关联的表Account和表DepartmentId进行的编辑却无法更新成功,求帮助。
更新的代码:
C# code
public ActionResult Edit(int id)        {            CompanyInfo companyInfo = CRMDB.CompanyInfos.Include(x => x.AccountInfos).Include(x => x.DepartmentIds).Where(x => x.id == id).Single();            return View(companyInfo);        }[HttpPost]        public ActionResult Edit(CompanyInfo companyInfo)        {            if (ModelState.IsValid)            {                                CRMDB.Entry(companyInfo).State = EntityState.Modified;                CRMDB.SaveChanges();                return RedirectToAction("Index");            }            return View(companyInfo);        }

编辑页面中的代码:
//前部分对Company对象编辑
//对象中关联到Account 的list 将其逐一显示成编辑状态

这部分是其中的List部分
<fieldset>
  <legend>单位下属部门信息列表</legend>
  <p>
  @Html.ActionLink("Create New","Create", "AccountInfo", new { id = Convert.ToInt32(@ViewBag.companyInfoid) })
  </p>
  <table class='nqtable' width='100%'>
  @if (Model.DepartmentIds != null && Model.DepartmentIds.Count > 0)
  {
  <tr class='nqtrheader'>

  <th>
  部门名称
  </th>
  <th>
  操作
  </th>
  </tr>
   
  foreach (var item in Model.DepartmentIds)
  {
  @Html.HiddenFor(model => item.id)
  item.CompanyInfoId = Model.id;
  @Html.HiddenFor(model =>item.CompanyInfoId)
  相关解决方案