public EmployeeWithOrgInfo EmployeeEditDirectReports(EmployeeEditDirectReports newItem)
{
// Attention - Update the self-referencing to-many association
// 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("Employee1").Include("Employee2")
.SingleOrDefault(e => e.EmployeeId == newItem.EmployeeId);
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
// "Employee1" is the badly-named to-many collection property
o.Employee1.Clear();
// Then, go through the incoming items
// For each one, add to the fetched object's collection
foreach (var item in newItem.EmployeeIds)
{
var a = ds.Employees.Find(item);
o.Employee1.Add(a);
}
// Save changes
ds.SaveChanges();
return Mapper.Map<EmployeeWithOrgInfo>(o);
}
}