title: Entity Framework Core Code-First: Cascade delete on a many-to-many relationship
body: <p>I'm working on an ASP.NET MVC 6 project with Entity-Framework Core (version <code>"EntityFramework.Core": "7.0.0-rc1-final"</code>) backed by a SQL Server 2012 express DB.</p>
  
  <p>I need to model a many-to-many relationship between a <code>Person</code> entity and an <code>Address</code> entity. 
  As per <a href="http://ef.readthedocs.org/en/latest/modeling/relationships.html#many-to-many" rel="noreferrer">this</a> guide I modeled it with a <code>PersonAddress</code>join-table entity, because this way I can store some extra info.  </p>
  
  <p>My <strong>goal</strong> is to set-up my system this way:</p>
  
  <ul>
  <li>If a <code>Person</code> instance is deleted, all the related <code>PersonAddress</code> instances must be deleted. All the <code>Address</code> instances they reference to must be deleted too, only if they are not related to other <code>PersonAddress</code> instances.</li>
  <li>If a <code>PersonAddress</code> instance is deleted, the <code>Address</code> instance it relates to must be deleted only if it is not related to other <code>PersonAddress</code> instances. All <code>Person</code> instances must live.</li>
  <li>If an <code>Address</code> instance is deleted, all the related <code>PersonAddress</code> instances must be deleted. All <code>Person</code> instances must live.</li>
  </ul>
  
  <p>I think most of the work must be done in the many-to-many relationship between <code>Person</code> and <code>Address</code>, but I expect to write some logic too. I will leave this part out of this question. What I'm interested in is how to configure my many-to-many relationship.</p>
  
  <p>Here is the current <strong>situation</strong>.</p>
  
  <p>This is the <code>Person</code> entity. Please note that this entity has got one-to-many relationships with other secondary entities.</p>
  
  <pre><code>public class Person
  {
      public int Id {get; set; } //PK
      public virtual ICollection&lt;Telephone&gt; Telephones { get; set; } //navigation property
      public virtual ICollection&lt;PersonAddress&gt; Addresses { get; set; } //navigation property for the many-to-many relationship
  }
  </code></pre>
  
  <p>This is the <code>Address</code> entity.</p>
  
  <pre><code>public class Address
  {
      public int Id { get; set; } //PK
      public int CityId { get; set; } //FK
      public City City { get; set; } //navigation property
      public virtual ICollection&lt;PersonAddress&gt; People { get; set; } //navigation property
  }
  </code></pre>
  
  <p>This is the <code>PersonAddress</code> entity.</p>
  
  <pre><code>public class PersonAddress
  {
      //PK: PersonId + AddressId
      public int PersonId { get; set; } //FK
      public Person Person {get; set; } //navigation property
      public int AddressId { get; set; } //FK
      public Address Address {get; set; } //navigation property
      //other info removed for simplicity
  }
  </code></pre>
  
  <p>This is the <code>DatabaseContext</code> entity, where all the relationships are described.</p>
  
  <pre><code>public class DataBaseContext : DbContext
  {
      public DbSet&lt;Person&gt; People { get; set; }
      public DbSet&lt;Address&gt; Addresses { get; set; }
  
      protected override void OnModelCreating(ModelBuilder builder)
      {            
          //All the telephones must be deleteded alongside a Person.
          //Deleting a telephone must not delete the person it refers to.
          builder.Entity&lt;Person&gt;()
              .HasMany(p =&gt; p.Telephones)
              .WithOne(p =&gt; p.Person);
  
          //I don't want to delete the City when I delete an Address
          builder.Entity&lt;Address&gt;()
              .HasOne(p =&gt; p.City)
              .WithMany(p =&gt; p.Addresses)
              .IsRequired().OnDelete(Microsoft.Data.Entity.Metadata.DeleteBehavior.Restrict);
  
          //PK for the join entity
          builder.Entity&lt;PersonAddress&gt;()
              .HasKey(x =&gt; new { x.AddressId, x.PersonId });
  
          builder.Entity&lt;PersonAddress&gt;()
              .HasOne(p =&gt; p.Person)
              .WithMany(p =&gt; p.Addresses)
              .IsRequired();
  
          builder.Entity&lt;PersonAddress&gt;()
              .HasOne(p =&gt; p.Address)
              .WithMany(p =&gt; p.People)
              .IsRequired();
      }
  }
  </code></pre>
  
  <p>Both <code>Telephone</code> and <code>City</code> entities have been removed for the sake of simplicity.</p>
  
  <p>This is the code for removing a <code>Person</code>.</p>
  
  <pre><code>Person person = await _context.People.SingleAsync(m =&gt; m.Id == id);
  try
  {
      _context.People.Remove(person);
      await _context.SaveChangesAsync();
  }
  catch (Exception ex)
  {
  
  }
  </code></pre>
  
  <p>As for my readings avoiding <code>.Include()</code> will let the DB take care of the eventual <code>CASCADE</code> deletes. I'm sorry but I don't remember the SO question where this concept was clarified.</p>
  
  <p>If I run this code I can seed the DB using <a href="https://stackoverflow.com/a/35798149/6011874">this workaround</a>. When I want to test-deleting a <code>Person</code> entity with the above code, I get this exception:</p>
  
  <pre><code>The DELETE statement conflicted with the REFERENCE constraint "FK_PersonAddress_Person_PersonId". The conflict occurred in database "&lt;dbName&gt;", table "&lt;dbo&gt;.PersonAddress", column 'PersonId'.
  The statement has been terminated.
  </code></pre>
  
  <p>I tested several relationship setups in the <code>DatabaseContext.OnModelCreating</code> method without any luck.  </p>
  
  <p>Finally, here's my <strong>question</strong>. How should I configure my many-to-many relationship in order to correctly delete a <code>Person</code> and its related entities from my application, according to the <strong>goal</strong> described before?</p>
  
  <p>Thank you all.</p>