title: How can I delete a many to many relationship in Entity Framework Core?
body: <p>I have two Entity Framework Entities.
  1) Employee
  2) Case</p>
  
  <p>I've modeled a many to many relationship in Entity Framework Core.</p>
  
  <p>I am able to add a relationship in like this:</p>
  
  <pre><code>    [HttpPost]
      public async Task&lt;Employee&gt; AddCaseEmployee([FromBody]EmployeeCase employeeCase)
      {
          Case lcase = await _caseGenericService.GetSingleIncludingAsync(employeeCase.CaseId);
  
          lcase.EmployeeCases = new List&lt;EmployeeCase&gt;();
          lcase.EmployeeCases.Add(new EmployeeCase
              {
                  CaseId = employeeCase.CaseId,
                  EmployeeId = employeeCase.EmployeeId
              }
          );
  
          await _caseGenericService.UpdateAsync(lcase);
  
          Employee employee = await _employeeGenericService.GetSingleIncludingAsync(employeeCase.EmployeeId);
          return employee;
      }
  </code></pre>
  
  <p>Now I am trying to remove one of the relationships like this:</p>
  
  <pre><code>    [HttpDelete]
      public async Task&lt;Employee&gt; DeleteCaseEmployee(long employeeId, long caseId)
      {
          Case lcase = await _caseGenericService.GetSingleIncludingAsync(caseId,
              a =&gt; a.EmployeeCases);
  
          //lcase.EmployeeCases.Remove(new EmployeeCase
          //{
          //    CaseId = caseId,
          //    EmployeeId = employeeId
          //}
          //);
          EmployeeCase employeeCase = 
              lcase.EmployeeCases.FirstOrDefault(ec =&gt; ec.EmployeeId == employeeId &amp;&amp; ec.CaseId == caseId);
          lcase.EmployeeCases.Remove(employeeCase);
  
          try
          {
              await _caseGenericService.UpdateAsync(lcase);
          }
          catch(Exception ex)
          {
  
          }
  
          Employee employee = await _employeeGenericService.GetSingleIncludingAsync(employeeId);
          return employee;
      }
  </code></pre>
  
  <p>You can see my first attempt commented out.
  So I tried the second way, just getting back the reference of the record I want to delete, removing it from the collection and then calling update.  But I get this error:</p>
  
  <p>"The association between entity types 'Case' and 'EmployeeCase' has been severed but the foreign key for this relationship cannot be set to null.
  If the dependent entity should be deleted, then setup the relationship to use cascade deletes."</p>
  
  <p>Here I don't need a Case or an Employee deleted.  I just need to delete the join record.
  And the only way to get into that record is to come in from a Case or an Employee to the relationship.</p>
  
  <p>If I make the EmployeeCase Object a Dbset the model won't build.</p>
  
  <p>Here is my relationship set up OnModelBuilding:</p>
  
  <pre><code>    modelBuilder.Entity&lt;EmployeeCase&gt;()
              .HasKey(ec =&gt; new { ec.EmployeeId, ec.CaseId });
  
          modelBuilder.Entity&lt;EmployeeCase&gt;()
              .HasOne(ec =&gt; ec.Employee)
              .WithMany(e =&gt; e.EmployeeCases)
              .HasForeignKey(ec =&gt; ec.EmployeeId);
  
          modelBuilder.Entity&lt;EmployeeCase&gt;()
              .HasOne(ec =&gt; ec.Case)
              .WithMany(c =&gt; c.EmployeeCases)
              .HasForeignKey(ec =&gt; ec.CaseId);
  
          // Get rid of Cascading Delete Circular references error.
          var type = modelBuilder.Model.GetEntityTypes().Single(t =&gt; t.Name == "Hrsa.Core.Generic.Model.Lerd.EmployeeCase");
          foreach (var relationship in type.GetForeignKeys())
          {
              relationship.DeleteBehavior = DeleteBehavior.Restrict;
          }
  </code></pre>
  
  <p>I had to turn off Deletes for the join Object, EmployeeCase, and it cannot be a DbSet.  If either of these steps are not followed the many to many model just will not build.</p>
  
  <p>All I need to do is to be able to delete this record.  I don't need to delete an Employee or Case.</p>
  
  <p>Here are the POCOs.</p>
  
  <pre><code>public class Employee : BaseEntity
  {
      [BindNever]
      public string Email { get; set; }
      [BindNever]
      public long OrganizationId { get; set; }
      [BindNever]
      public string Supervisor { get; set; }
      [BindNever]
      public string SupervisorEmail { get; set; }
      [BindNever]
      public string FirstName { get; set; }
      [BindNever]
      public string LastName { get; set; }
      public string Notes { get; set; }
      [BindNever]
      public  long BargainingUnitId { get; set; }
      [BindNever]
      public long PayPlanId { get; set; }
      [BindNever]
      public long GradeRankId { get; set; }
      [BindNever]
      public long PositionTitleId { get; set; }
      [BindNever]
      public long SeriesId { get; set; }
      public bool IsUnionEmployee { get; set; }
      public virtual Organization Organization { get; set; }
      public virtual BargainingUnit BargainingUnit { get; set; }
      public virtual PayPlan PayPlan { get; set; }
      public virtual GradeRank GradeRank { get; set; }
      public virtual PositionTitle PositionTitle { get; set; }
      public virtual  Series Series { get; set; }
      public virtual ICollection&lt;UnionHours&gt; UnionHours { get; set; }
      [NotMapped]
      public string UnionEmployeeYesNo =&gt; (IsUnionEmployee) ? "Yes" : "No";
  
      public virtual ICollection&lt;EmployeeCase&gt; EmployeeCases { get; set; }
  </code></pre>
  
  <p>}</p>
  
  <pre><code>public class Case : BaseEntity
  {
      #region Common Case Properties
      public long InitialContactId { get; set; }
      public virtual Employee InitialContact { get; set; }
      [DataType(DataType.Date)]
      public DateTime? InitialConsultDate { get; set; }
      public string LerSpecialistId { get; set; }
      public virtual AppUser LerSpecialist { get; set; }
      public string Notes { get; set; }
  
      public bool IsDeleted { get; set; }
      public CaseType CaseType { get; set; }
      #endregion
  
      #region EmployeeCase Properties
      //public long PrimaryEmployeeId { get; set; }
      //public virtual Employee PrimaryEmployee {get;set;}
      public virtual ICollection&lt;EmployeeCase&gt; EmployeeCases { get; set; }
      #endregion
  
      #region NonEmployeeCase Properties
      //public long PrimaryNonEmployeeId { get; set; }
      //public virtual Employee PrimaryEmployee {get;set;}
      public virtual ICollection&lt;NonEmployeeCase&gt; NonEmployeeCases { get; set; }
      #endregion
  }
  </code></pre>
  
  <p>and the join table (which again, is not a DbSet, but everything has been working as far as adding relationships.  Now just can't delete.)</p>
  
  <pre><code>public class EmployeeCase
  {
      [ForeignKey("Id")]
      public long EmployeeId { get; set; }
      public Employee Employee { get; set; }
      [ForeignKey("Id")]
      public long CaseId { get; set; }
      public Case Case { get; set; }
  
  }
  </code></pre>
  
  <p>How can I delete this many to many relationship record?</p>