CSharpBeginner
CSharpBeginner

Reputation: 1725

Entity Framework - Cascade deleting

Let's assume I have got 2 classes :

public class Photo 
{
     public int Id {get;set;}
     public string Name {get;set;}
     public int AlbumId {get;set;

     publiv virtual Album Album {get;set;}
}

public class Album
{
     public int Id {get;set;}
     public decimal Price {get;set;}

     public ICollection<Photo> Photos {get;set;}
}

Now i want to delete all albums with price for example 2. I have tried :

Context.RemoveRange(Context.Albums.Where(x = > x.Price == 2))

It would be fine, but before deleting the Albums I need to delete every photo with AlbumId I want to delete.

Upvotes: 0

Views: 94

Answers (2)

Joshua Powers
Joshua Powers

Reputation: 72

EF does not do cascade deletes itself. It relies on the database definition to be correct, and then assumes that the database will perform cascade deletes if specified. See this article for more info. You will have to use Fluent as the other user pointed out, EF does not do that on its own.

Upvotes: 1

Anton Kozlovsky
Anton Kozlovsky

Reputation: 213

use Fluent API in Context to apply Cascade deleting

modelBuilder.Entity<Photo>()
                        .HasRequired(c => c.Album)
                        .WithMany(a => a.Photoes)
                        .WillCascadeOnDelete(true);

Upvotes: 1

Related Questions