I have an email service which stores email requests in a database (due to legacy reasons). There are two entities, an EmailRequest
public class EmailRequest
{
[Key]
public Guid ID { get; set; }
public bool Sent {get; set;
//Other props
public virtual List<Attachment> Attachments { get; set; }
}
And Attachments for a given email
public class Attachment
{
[Key]
public Guid Id { get; set; }
//Other props
public virtual EmailRequest EmailRequest { get; set;}
}
Insertions in to the DB are working fine – the email record goes in the ‘parent’ table and zero-to-many attachments are inserted in the attachments ‘child’ table. When the email has been sent I want to update the Sent flag in the parent table and delete any attachments as they are just wasting space. However, in my DBContext class when I call
Attachments.RemoveRange(Attachments.Where(a => a.EmailRequest.ID == identifier));
All the attachments are deleted but the parent (EmailRequest) is also being deleted. Any ideas what is causing this? I’ve turned off cascade deletions which did nothing as I suspected, as I’m deleting a child record, not a parent. However, I don’t know how to tell Entity Framework (6.1.3) not to delete the parent.
Any ideas?
EDIT
So as suggested in the comments, it doesn't look like EF itself is performing the delete, becuase if I go into SSMS and delete from the attachments table, its also deleting the parent. Must be something in the entity here.
EDIT 2
So if I use request.attachments.clear()
instead of Attachments.RemoveRange()
it clears the parent down (and the foreign key reference in Attachment) but leaves the attachment, so the exact opposite of what I want to do!