I have this model :
public class FileUpload
{
public int FileUploadId { get; set; }
public string FileName { get; set; }
}
public class Company
{
public int CompanyId { get; set; }
public string Name { get; set; }
public FileUpload Logo { get; set; }
public int? LogoId { get; set; }
public FileUpload Catalog { get; set; }
public int? CatalogId { get; set; }
}
public class Ads
{
public int AdsId { get; set; }
public string Name { get; set; }
public FileUpload Picture { get; set; }
public int? PictureId { get; set; }
}
public class TestContext : DbContext
{
public DbSet<Company> Companies { get; set; }
public DbSet<Ads> Adses { get; set; }
public DbSet<FileUpload> FileUploads { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Ads>()
.HasOptional(a => a.Picture)
.WithMany()
.HasForeignKey(a => a.PictureId)
.WillCascadeOnDelete();
modelBuilder.Entity<Company>()
.HasOptional(a => a.Logo)
.WithMany()
.HasForeignKey(a => a.LogoId)
.WillCascadeOnDelete();
modelBuilder.Entity<Company>()
.HasOptional(a => a.Catalog)
.WithMany()
.HasForeignKey(a => a.CatalogId)
.WillCascadeOnDelete();
}
}
this code is not working in EF migration!
I want :
– every company has optional Logo or Catalog and every Ads has optional Picture.
– the FileUpload record can be deleted directly
– cascade delete
how to do this?!
Do you want that a
FileUploadis deleted by cascading delete when aCompanyorAdsis deleted?This would make no sense because
FileUploadis the principal in all three relationships andCompanyandAdsare the dependents. You cannot cascading delete the principal when a dependent is deleted. It would fail in most cases anyway because in a one-to-many relationship theFileUploadcould be used by many other companies or ads. If you delete one of them and theFileUploadwould be deleted by cascading delete you would violate a foreign key constraint for the other companies and ads.In your model you could only have a cascading delete so that
CompanyandAdsare deleted when aFileUploadis deleted (which sounds strange to me though). Even that would not work with your Fluent mapping because you have configured multiple cascading delete paths fromFileUploadtoCompanywith the two relationships. SQL Server doesn’t allow such relationships. You would have to remove at least one cascading delete.In you model you need to delete the
FileUploadrecords manually when aCompanyandAdsis deleted after your have checked if theFileUploadisn’t used by another company or ads.If you know for sure in your business logic that a given
FileUploadcannot be used by more than one company or ads and that the sameFileUploadis never used by a company and by an ads, it is getting simpler (example for deleting a company):