0

Is this odd?

When deleting relationships of one to many, if a the relationship is optional and you delete the parent object the rest will remain orphan and it does not cascade delete.

    var album = new Album
                {
                    Name = "Test Album",
                    Description = "Test Album Description",
                    Images = new Collection<Image>
                    {
                        new Image {
                            Name = "Image 1",
                            Description = "Image 1 Description"
                        },
                        new Image {
                            Name = "Image 2",
                            Description = "Image 2Description"
                        },
                    }
                };

            albumRepository.Add(album);
            albumRepository.UnitOfWork.Commit();

Under the Image Entity I got the AlbumId as Nullable since some images can be orphaned.

And then I call.

albumRepository.Delete(toRemove);
albumRepository.UnitOfWork.Commit();

The Album gets deleted but the images that where once related are Orphaned and their AlbumId is removed from the row.

Michael D. Irizarry
  • 6,186
  • 5
  • 30
  • 35

1 Answers1

1

This did it.

modelBuilder.Entity<Image>()
.HasOptional(d => d.Album)
.WithMany(d => d.Images)
.WillCascadeOnDelete(true);
Michael D. Irizarry
  • 6,186
  • 5
  • 30
  • 35