Entity Framework: how to enable cascading deletion in unidirectional objects

There are two objects, for example, below:

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 to configure cascading file deletion for deletion? Please note that I do not need navigation from File to Business .

UPDATE:

You can find the modelBuilder configuration as shown below:

  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 received:

Representation of the FOREIGN KEY constraint "FK_dbo.Files_dbo.Businesses_Business_Id1" in the Files table can cause loops or multiple cascading paths. Specify ON. REMOVE NO ACTION or ON. UPDATE NO ACTION or change other FOREIGN KEY constraints. Could not create restriction

+6
source share
1 answer

If you like the individual configuration classes, you can try something like this:

  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(); } } 

If you don't miss lambda within .WithOptional() or .WithRequired() , then the other side has no navigation properties.

+5
source

Source: https://habr.com/ru/post/952722/


All Articles