tickwave
tickwave

Reputation: 3455

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

Upvotes: 4

Views: 10392

Answers (4)

Johnathan Barclay
Johnathan Barclay

Reputation: 20373

There's no need to explicitly remove the dependent entity from the DbContext; if a dependent entity should always be deleted when removed from it's principal entity, this can be achieved through configuration on the DbContext, using OnDelete:

protected override void OnModelCreating(ModelBuilder builder)
{
    builder
        .Entity<HomeSection2>()
        .HasMany(x => x.HomeSection2Detail)
        .WithOne(x => x.HomeSection2)
        .OnDelete(DeleteBehavior.Cascade); // Causes dependent entity to be deleted
}

Upvotes: 5

mosi98
mosi98

Reputation: 663

you use direct from RemoveRange or Remove DbContext

 _db.RemoveRange(obj2detail);

Upvotes: 0

CodeNotFound
CodeNotFound

Reputation: 23240

You need to do the following. Explainations added as comments in the snippet:

var obj2detail = obj2.HomeSection2Detail.Where(w => w.ID == detail.ID).FirstOrDefault();
if (obj2detail != null)
{
    // this line of code only delete the relationship.
    obj2.HomeSection2Detail.Remove(obj2detail);

    // If you want to delete the entity you need the DbContext help 
    // and your HomeSection2Details DbSet<HomeSection2Detail> like below
    yourDbContext.HomeSection2Details.Remove(obj2detail);
}

Upvotes: 2

Mohammed Noureldin
Mohammed Noureldin

Reputation: 16976

You need to remove the entity explicitly from HomeSection2Details DbSet.

dbContext.HomeSection2Details.Remove(obj2detail);

Upvotes: 4

Related Questions