简体   繁体   中英

Deleting the child record deletes a parent record in entity

I am working on an asp.net application. I use Entity framework to represent my tables. I have a model with two foreign keys. One of the seems to be giving me troubles as when I try to delete a record from the child model, the parent gets deleted as well. Here are my models:

public class Class1
{
    public Class1()
    {
        this.Children= new HashSet<Child>();
    }

    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }

    public bool variable{ get; set; }

    [ForeignKey("Class0")]
    public long Class0_Id { get; set; }

    public virtual CLass0 CLass0{ get; set; }

    public virtual ICollection<Child> Children{ get; set; }
}

public class CHild
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }

    public bool variable5{ get; set; }

    [ForeignKey("CLass1")]
    public long Class1_Id { get; set; }

    public virtual Class1 Class1{ get; set; }

    [ForeignKey("AnotherClass")]
    public long AnotherClass_Id { get; set; }

    public virtual AnotherClass AnotherClass{ get; set; }
}

my problem is that when I try to delete a record from Child class, the related Class0 record gets deleted as well

You don't have any other code posted, but I am going to take a guess anyway. Most likely, you are loading the child and the parent at the same time. Thus, the child has a reference to the parent. You may need to check the FluentAPI (Foreign Key) relationship between these two if you set it up elsewhere as it might be setup that the child is the parent instead.

The other thing you can do is right before you delete the child, just set Class1 property on the child to null. That should cause it to not automatically include it in the delete.

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