AssocManyToMany.Controllers.Manager.EmployeeEditJobDuties C# (CSharp) Метод

EmployeeEditJobDuties() публичный Метод

public EmployeeEditJobDuties ( EmployeeEditJobDuties newItem ) : EmployeeWithJobDuties
newItem EmployeeEditJobDuties
Результат EmployeeWithJobDuties
        public EmployeeWithJobDuties EmployeeEditJobDuties(EmployeeEditJobDuties newItem)
        {
            // Attempt to fetch the object

            // When editing an object with a to-many collection,
            // and you wish to edit the collection,
            // MUST fetch its associated collection
            var o = ds.Employees.Include("JobDuties")
                .SingleOrDefault(e => e.Id == newItem.Id);

            if (o == null)
            {
                // Problem - object was not found, so return
                return null;
            }
            else
            {
                // Update the object with the incoming values

                // First, clear out the existing collection
                o.JobDuties.Clear();

                // Then, go through the incoming items
                // For each one, add to the fetched object's collection
                foreach (var item in newItem.JobDutyIds)
                {
                    var a = ds.JobDuties.Find(item);
                    o.JobDuties.Add(a);
                }
                // Save changes
                ds.SaveChanges();

                return Mapper.Map<EmployeeWithJobDuties>(o);
            }
        }

Usage Example

        public ActionResult EmployeeAndJobDuties(int?id, EmployeeEditJobDuties newItem)
        {
            // Validate the input
            if (!ModelState.IsValid)
            {
                // Our "version 1" approach is to display the "edit form" again
                return(RedirectToAction("edit", new { id = newItem.Id }));
            }

            if (id.GetValueOrDefault() != newItem.Id)
            {
                // This appears to be data tampering, so redirect the user away
                return(RedirectToAction("index"));
            }

            // Attempt to do the update
            var editedItem = m.EmployeeEditJobDuties(newItem);

            if (editedItem == null)
            {
                // There was a problem updating the object
                // Our "version 1" approach is to display the "edit form" again
                return(RedirectToAction("ByEmployee", new { id = newItem.Id }));
            }
            else
            {
                // Show the details view, which will have the updated data
                return(RedirectToAction("ByEmployeeWithJobDuties", new { id = newItem.Id }));
            }
        }