简体   繁体   中英

Prevent deletion of child record from deleting parent

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!

If you can see the difference I am first grabbing the parent entity and then deleting his child collections. where as you are deleting the child entities directly. I cant see how the parent entity would be deleted in this instance since it is sitting right there in memory for you to see. if it does then I would check my DB constraints big time to see if entity framework has added an unwanted constraint.

using (var context = new MyContext())
{
    var parent = context.Parents.Include(p => p.Children)
    .SingleOrDefault(p => p.Id == parentId);

    foreach (var child in parent.Children.ToList())
    context.Children.Remove(child);

    context.SaveChanges();
}

I'm hoping the method above gives you more debugging options or just eliminates the issue. I'm also adding a link to let you check the SQL generated by Entity Framework for more debugging options (see below)

How do I view the SQL generated by the Entity Framework?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM