title: Using Entity framework generic repository with web api and many to many relationships
body: <p>In my Web API application I implemented the generic repository pattern as described in this <a href="http://www.tugberkugurlu.com/archive/generic-repository-pattern-entity-framework-asp-net-mvc-and-unit-testing-triangle" rel="nofollow noreferrer">post</a>.
  So now whenever I create a Crud Api controller I use a service that uses a repository to talk to database. </p>
  
  <p>Lets say I have those two entity models</p>
  
  <pre><code>public class Student
  {
      public Student() 
      {
          this.Courses = new HashSet&lt;Course&gt;();
      }
  
      public int StudentId { get; set; }
      [Required]
      public string StudentName { get; set; }
      public virtual ICollection&lt;Course&gt; Courses { get; set; }
  }
  
  public class Course
  {
       public Course()
       {
          this.Students = new HashSet&lt;Student&gt;();
       }
      public int CourseId { get; set; }
      public string CourseName { get; set; }
      public virtual ICollection&lt;Student&gt; Students { get; set; }
  }
  </code></pre>
  
  <p>And my Controllers and service classes are as follows</p>
  
  <pre><code>public class StudentsController 
  {
      private StudentsService studentService;
  
     // CRUD Api Methods...
  }
  
  public class StudentService
  {
      private StudentsRepository studentsRepo;
  
     // CRUD Api Methods...
  }
  </code></pre>
  
  <p>In the front end whenever I send a post request to the api like:</p>
  
  <pre><code>/api/Students : Post
  {
    "id": 9999,
     "studentName":"string",
     "Courses":[
      {
        "id":13
      }, 
      {
        "id":25
      }]
  }
  </code></pre>
  
  <p>For some strange reason the repository tries to create those new two courses even thought they exists in the database and it fails.
  If I change the relationship to one to many and change the Post to send only one course id like this</p>
  
  <pre><code>/api/Students : Post
  {
    "id": 9999,
     "studentName":"string",
      "CourseId":13
  }
  </code></pre>
  
  <p>The EF saves the changes successfully.</p>
  
  <p>I managed to make this work by having both repositories instantiated in my 
  Students service and then grab all the ids from the incoming Student model
  make a call to the courseRepo to fetch all the Courses and override the incoming
  Student.Courses with the ones I fetched from the database. </p>
  
  <p>This works but it seems like a bad practice to me. I thought that the whole purpose of doing this service-repository was to have a clean backend , something like MicroServices architecture. </p>