4

I have 2 entities: Reports and FileRequests. There is a many-to-many relationship between these.

So Report.cs has

 public virtual ICollection<FileRequest> FileRequests { get; set; }

And FileRequest.cs has

 public ICollection<Report> Reports { get; set; }

Entity Framework has generated a join table (FileRequestReports) and cascade delete always works for the join table entries. What I want to happen is deleting a filerequest deletes the associated reports, but deleting a report DOES NOT delete the associated filerequests. The associated join table entries should always be deleted.

Note: the ManyToManyCascadeDeleteConvention is on.

Is there a relatively easy way to do with with EF and cascade delete?

Thanks in advance.

Kevin Rock
  • 249
  • 3
  • 11
  • Is there other information in `FileRequestReports`? Usually auto-generated many-to-many tables use the Ids of the two related tables as keys. If you delete one end of the relationship, it is set up to cascade deletes because the foreign key restraint would fail. In order to make this work, you would need to create your own `FileRequestReport` entity, give it a unique key, make the `ReportId` field required, and make the `FileRequestId` nullable. – Sam Feb 22 '16 at 17:11
  • No, FileRequestReports only consists of two foreign keys – Kevin Rock Feb 22 '16 at 19:19
  • Possible duplicate of [EntityFramework CodeFirst: CASCADE DELETE for same table many-to-many relationship](https://stackoverflow.com/questions/32655959/entityframework-codefirst-cascade-delete-for-same-table-many-to-many-relationsh) – Mamun Apr 25 '19 at 10:09

1 Answers1

3

I believe the only way to achieve this is creating a class to represent the many-to-many relationship. Like this:

public class ReportFileRequest
{
    public int ReportId { get; set; }

    public int FileRequestId { get; set;}

    public virtual Report Report { get; set;}

    public virtual FileRequest FileRequest { get; set; }
}

You have to update Report:

public virtual ICollection<ReportFileRequest> ReportFileRequests { get; set; }

And FileRequest:

public virtual ICollection<ReportFileRequest> ReportFileRequests { get; set; }

Mapping:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<ReportFileRequest>()
        .HasKey(i => new { i.ReportId, i.FileRequestId });

    model.Entity<ReportFileRequest>()
       .HasRequired(i => i.Report)
       .WithMany(i => i.ReportFileRequests)
       .WithForeignKey(i => i.ReportId)
       .WillCascadeOnDelete(true);

    model.Entity<ReportFileRequest>()
       .HasRequired(i => i.FileRequest)
       .WithMany(i => i.ReportFileRequests)
       .WithForeignKey(i => i.FileRequestId)
       .WillCascadeOnDelete(false);

}
Fabio
  • 11,892
  • 1
  • 25
  • 41