Reputation: 3455
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.
Upvotes: 4
Views: 10392
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
Reputation: 663
you use direct from RemoveRange or Remove DbContext
_db.RemoveRange(obj2detail);
Upvotes: 0
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
Reputation: 16976
You need to remove the entity explicitly from HomeSection2Details
DbSet.
dbContext.HomeSection2Details.Remove(obj2detail);
Upvotes: 4