Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework: How to enable cascade delete on one way related entities

There are Two Entities such as bellow:

public class Business
{
    public int Id {get; set;}

    public File Logo {get; set;}
    public int? LogoId {get; set;}

    public File Video {get; set;}
    public int? Video {get; set;}

    public ICollection<File> Images {get; set;}
}

public class File
{
    // some file props, such as Id, Name, ...
}

How can I configure cascade delete for files on business delete? Please consider that I don't need any navigation from File to Business.

UPDATE:

You may find the modelBuilder configuration as bellow:

        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

        modelBuilder.Entity<Entities.Business>()
            .HasOptional(b => b.Logo)
            .WithOptionalPrincipal()
            .WillCascadeOnDelete();

        modelBuilder.Entity<Entities.Business>()
            .HasOptional(b => b.Video)
            .WithOptionalPrincipal()
            .WillCascadeOnDelete();

        modelBuilder.Entity<Entities.Business>()
            .HasMany(b => b.Images)
            .WithOptional()
            .WillCascadeOnDelete();

and here is the error I've got:

Introducing FOREIGN KEY constraint 'FK_dbo.Files_dbo.Businesses_Business_Id1' on table 'Files' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint

like image 480
Reza Owliaei Avatar asked Aug 29 '13 09:08

Reza Owliaei


People also ask

How do I enable cascade delete in Entity Framework?

Cascade delete automatically deletes dependent records or sets null to ForeignKey columns when the parent record is deleted in the database. Cascade delete is enabled by default in Entity Framework for all types of relationships such as one-to-one, one-to-many and many-to-many.

How do I remove a one to many relationship in Entity Framework?

after manual set the property,single call to "dbContext. As. Remove(someA)" work as expected!

Will cascade on delete EF core?

The EF Core in-memory database does not currently support cascade deletes in the database.


1 Answers

If you like to use seperate configuration classes you could try something like that:

  public class BusinessConfiguration : EntityTypeConfiguration<Business>
  {
        public BusinessConfiguration()
        {
            HasMany(x => x.Images).WithOptional().WillCascadeOnDelete();
            HasOptional(x => x.Logo).WithOptional().WillCascadeOnDelete();
            HasOptional(x => x.Video).WithOptional().WillCascadeOnDelete();
        }
  }

When you do not pass a lambda within .WithOptional() or .WithRequired() means the other side has no navigation properties.

like image 119
dasheddot Avatar answered Oct 02 '22 07:10

dasheddot