发布的背面模型上的.ADD不会将数据添加到数据库中

时间:2015-01-30 09:03:27

标签: asp.net asp.net-mvc entity-framework asp.net-mvc-5

我有以下Post动作方法,我传递一个表示客户的int []数组并将它们添加到当前技能对象: -

[HttpPost]

        public async Task<ActionResult> AssignCustomersToSkill(Skill skill, int[] selectedCustomers)
        {
            try
            {
                var dbskill = db.Skills.SingleOrDefault(a => a.SkillID == skill.SkillID);
                var tempcustomers = dbskill.Customers.ToList();
                foreach (var c in tempcustomers)
                {
                    dbskill.Customers.Remove(c);
                }


                foreach (var sC in selectedCustomers)
                {
                    dbskill.Customers.Add(db.Customers.Find(sC));
                }
                await db.SaveChangesAsync();
                TempData["message"] = string.Format("{0} Customer/s have been Assigned", String.Empty);
                if (Request.IsAjaxRequest())
                {
                    return Json(new { ISsuccess = true });
                }

                return RedirectToAction("Edit", new { id = skill.SkillID });

            }         


        }

以上工作正常,客户列表将分配给dbskill对象。

但我无法理解的是,如果我修改我的上述操作方法(通过用skill.Customers.Add替换dbskill.Customers.Add),那么我将把客户添加到已发布的后退对象,这是传递给action方法,而不是dbskill,如下所示,那么DB上不会发生任何影响,而且我也不会得到任何异常: -

[HttpPost]

        public async Task<ActionResult> AssignCustomersToSkill(Skill skill, int[] selectedCustomers)
        {
            try
            {
                var dbskill = db.Skills.SingleOrDefault(a => a.SkillID == skill.SkillID);
                var tempcustomers = dbskill.Customers.ToList();
                foreach (var c in tempcustomers)
                {
                    skill.Customers.Remove(c);
                }


                foreach (var sC in selectedCustomers)
                {
                    skill.Customers.Add(db.Customers.Find(sC));
                }
                await db.SaveChangesAsync();
                TempData["message"] = string.Format("{0} Customer/s have been Assigned", String.Empty);
                if (Request.IsAjaxRequest())
                {
                    return Json(new { ISsuccess = true });
                }

                return RedirectToAction("Edit", new { id = skill.SkillID });

            }
            catch (Exception e)
            {
                ModelState.AddModelError(string.Empty, "Error Occured while processing your request.");
            }

                    }

所以有人可以为什么我的第二个动作方法不起作用?虽然在两种动作方法中,技能对象(dbskill或回发技能)具有相同的ID?

由于

0 个答案:

没有答案