I'm currently developing a system that generate and manage thumbnails for images in a site. Basically to improve loading time, creating smaller images before so it doesn't need any preprocessing for each request or load the original big image.
The creation is currently working fine but I'm having trouble to remove the images (original and generated). When I remove direct from the database it works just fine with a simple delete, but when I'm doing it by code it doesn't work.
My Image table is split in two classes
public class Image(){
public int Id{ get; set;}
public int? MainImageId{ get; set;};
public string Description{ get; set;}
public virtual Image MainImage{ get; set;}
public virtual ImageContent Content{ get; set;}
public virtual ICollection<Image> Variations{ get; set;}
}
public class ImageContent(){
public int ImageId { get; set; }
public byte[] Raw { get; set; }
public virtual Image Image { get; set; }
}
They are build as
modelBuilder.Entity<Image>()
.HasRequired(x => x.Content)
.WithRequiredDependent(x => x.Image);
modelBuilder.Entity<Image>()
.ToTable("Images");
modelBuilder.Entity<ImageContent>()
.HasKey(x => x.ImageId)
.ToTable("Images");
modelBuilder.Entity<Image>()
.HasMany(i => i.Variations)
.WithOptional(i => i.MainImage)
.HasForeignKey(v => v.MainImageId);
And my remove function is
public void Delete(int id){
var image = context.Set<Image>().Include("Variations").FirstOrDefault(i => i.Id == id);
if (image != null) {
foreach(Image variation in image.Variations) {
context.Set<Image>().Remove(variation);
}
context.Set<Image>().Remove(image);
context.SaveChanges();
}
}
But when I run the Delete function I get an DbUpdateException with the message Invalid data encountered. A required relationship is missing. Examine StateEntries to determine the source of the constraint violation.
The error is thrown when context.SaveChanges()
runs.
I've already tried to include all the dependents like Content and Variations and can't find any other reason why this error is being thrown.
Previously the class didn't have a self reference and everything worked just fine. Does anybody know what I can do to fix this?