Свой ответ я буду строить исходя из того что фактическое редактирование происходит на отсоединенной записи, либо же для в gui
используются view model
, dto
объекты.
Для того что бы entity-framework вас понял необходимо сделать следующее
- Присоединить к контексту существующую запись, например так:
var student = _context.Students.Attach(new Student {Id = model.Id});
- Загрузить связанные курсы при помощи навигационного свойства:
context.Entry(student).Collection(x=>x.Cources).Load();
Необходимо понять какие курсы необходимо добавить а какие удалить.
3.1. var deletedCources = student.Cources.Except(model.Cources, cource=>cource.Id);
3.2. var addedCources = model.Cources.Except(student.Cources, cource=>cource.Id);
Затем соответственно необходимо удалить/добавить курсы студенту: deletedCources.ForEach(cource=>student.Cources.Remove(cource));
, addedCources.ForEach(cource=>student.Cources.Add(cource));
В заключении говорим ef что объект студент был изменен и сохраняем: _context.Entry(student).State = EntityState.Modified;
_context.SaveChanges();
public void EditStudent(StudentViewModel model)
{
using(var _context = new DefaultContext())
{
var student = _context.Students.Attach(new Student {Id = model.Id});
_context.Entry(student).Collection(x=>x.Cources).Load();
var deletedCources = student.Cources.Except(model.Cources, Cource=>cource.Id);
var addedCources = model.Cources.Except(student.Cources, cource=>cource.Id);
deletedCources.ForEach(cource=>student.Cources.Remove(cource));
addedCources.ForEach(cource=>student.Cources.Add(cource));
_context.Entry(student).State = EntityState.Modified;
_context.SaveChanges();
}
}
Перегруженная версия метода Except()
используемая в примере
public static IEnumerable<T> Except<T, TKey>(this IEnumerable<T> items,
IEnumerable<T> other,
Func<T, TKey> getKey)
{
return from item in items
join otherItem in other on getKey(item) equals getKey(otherItem) into tempItems
where !tempItems.Any()
select item;
}
адаптация статьи