2

I have a one-to-many relationship defined below

public class Student{
   [key]
   public string Id{get; set;}
   public string name{get; set:}
   public virtual List<Enrollment> Enrol{get; set;}
}

public class Enrollment{
  public int Id{get; set;}

  [ForeignKey("student")]
  public String StudentId{get; set;}
  Public string ISC{get; set;}
  public virtual Student student{get; set;}

}

I have a form allowing me to edit a Student entity including adding or removing some enrollments. When saving this data after the form is submitted, does the enrollments get updated too, or do I have to update the enrollments separately? Ideally, should the enrollment by deleted and then re-inserted or just updated (and doing inserts only when there are more new items than there are existing ones)?

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
jpo
  • 3,959
  • 20
  • 59
  • 102

1 Answers1

1

You need to walk the graph. EF doesn't update relationships automatically.

This response has a good example of insert/update delete child objects: The relationship could not be changed because one or more of the foreign-key properties is non-nullable

There is also a good extension method that adds graph walking functionality: https://github.com/refactorthis/GraphDiff

Community
  • 1
  • 1
Michael Finger
  • 1,110
  • 9
  • 9