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
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.
after manual set the property,single call to "dbContext. As. Remove(someA)" work as expected!
The EF Core in-memory database does not currently support cascade deletes in the database.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With