1

Есть следующая доменная модель:

public class Student
{
    public int Id {get;set;}
    public virtual ICollection<Cource> Cources {get;set;}

    public Student()
    {
        this.Cources = new HashSet<Cource>();
    }
}

public class Cource
{
    public int Id {get;set;}
    public virtual ICollection<Student> Students {get;set;}

    public Cource()
    {    
        this.Students = new HashSet<Student>();    
    }    
}

Как мне изменить(удалить) связь между студентом и курсом, т.е. добавить студенту новый курс, удалить существующий?

1 ответ 1

1

Свой ответ я буду строить исходя из того что фактическое редактирование происходит на отсоединенной записи, либо же для в gui используются view model, dto объекты.

Для того что бы вас понял необходимо сделать следующее

  1. Присоединить к контексту существующую запись, например так: var student = _context.Students.Attach(new Student {Id = model.Id});
  2. Загрузить связанные курсы при помощи навигационного свойства: context.Entry(student).Collection(x=>x.Cources).Load();
  3. Необходимо понять какие курсы необходимо добавить а какие удалить.

    3.1. var deletedCources = student.Cources.Except(model.Cources, cource=>cource.Id);

    3.2. var addedCources = model.Cources.Except(student.Cources, cource=>cource.Id);

  4. Затем соответственно необходимо удалить/добавить курсы студенту: deletedCources.ForEach(cource=>student.Cources.Remove(cource)); , addedCources.ForEach(cource=>student.Cources.Add(cource));

  5. В заключении говорим 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;

}

адаптация статьи

4
  • Зачем так сложно, с .DefaultIfEmpty() и прочим? where tempItems.Count() == 0 и никакой магии. 26 апр 2017 в 6:28
  • @PavelMayorov я взял код из вот этой статьи.
    – Bald
    26 апр 2017 в 6:31
  • Это же не повод писать ерунду? :-) Та статья, по всей видимости, была написана человеком, который хорошо знает SQL и плохо знает LINQ... 26 апр 2017 в 6:32
  • @PavelMayorov <strike>тогда наверно возможно вместо Count() использовать Any(). счас проверю и отредактирую.</strike> сначала написал, потом увидел вашу правку :)
    – Bald
    26 апр 2017 в 6:36

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.