I have two objects. Profile and ProfileImage. My context is set up to fetch a Profile and I want to delete a ProfileImage (not just the reference) through the Profile, first fetching the profile then getting a profileImage and removing it like this:
using (var dbContext = new myContext())
{
var profile = dbContext.profiles.Where(i => i.ApplicationUserGuid == userId).First();
var profileImageToDelete = profile.profileImages.Where(i => i.YogaProfileImageId == Convert.ToInt32(idToRemove)).First();
profile.ProfileImages.Remove(profileImageToDelete);
dbContext.SaveChanges();
}
But I'm getting an error when saving that says:
The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
Here are my two entity objects:
public class Profile
{
public Profile()
{
ProfileImages = new List<ProfileImage>();
}
[Key]
public int ProfileId { get; set; }
[Column(TypeName = "VARCHAR")]
[StringLength(36)]
[Index]
public string ApplicationUserGuid { get; set; }
public bool IsActive { get; set; }
public virtual ICollection<ProfileImage> ProfileImages { get; set; } //one-to-many }
public class ProfileImage
{
[Key]
public int ProfileImageId { get; set; }
public int ProfileRefId { get; set; }
[ForeignKey("ProfileRefId")]
public virtual Profile Profile { get; set; }
public byte[] CroppedImage { get; set; }
public byte[] ImageThumbnailCropped { get; set; }
public bool IsMainImage { get; set; }
}
I read something about cascading deletes but not sure if this is what I need to do or what I need to do to get the image to delete completely from the ProfileImage table.