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

c# code-first entity-framework

Question

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

1
6
8/29/2013 10:32:36 AM

Accepted Answer

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.

5
8/29/2013 9:07:46 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow