Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you delete Child from Parent entities in EF Core?

I have these class

public class HomeSection2
{
    public HomeSection2()
    {
        HomeSection2Detail = new List<HomeSection2Detail>();
    }

    public Guid ID { get; set; }
    public string Title { get; set; }
    public string Header { get; set; }

    public virtual List<HomeSection2Detail> HomeSection2Detail { get; set; }
}

public class HomeSection2Detail
{
    public Guid ID { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Link { get; set; }
    public int? Sequence { get; set; }

    public virtual HomeSection2 HomeSection2 { get; set; }
}

When I call

var obj2detail = obj2.HomeSection2Detail.Where(w => w.ID == detail.ID).FirstOrDefault();
if (obj2detail != null)
{
    obj2.HomeSection2Detail.Remove(obj2detail);
}  

From my Application, it will only remove the relationship but not the record in the Database.

enter image description here

like image 775
warheat1990 Avatar asked Jan 03 '23 06:01

warheat1990


1 Answers

You need to remove the entity explicitly from HomeSection2Details DbSet.

dbContext.HomeSection2Details.Remove(obj2detail);
like image 200
Mohammed Noureldin Avatar answered Jan 14 '23 09:01

Mohammed Noureldin