I wish to use this in my database context class:
OnDelete(DeleteBehavior.Cascade)
But it's on a SQL Server table with no foreign key.
My parent table, TransplantList
, has a column heartId
, which corresponds to a table HeartList
which looks like this in SQL Server:
heartId
heartName
heartLocation
heartType
TransplantList
can only have one heartId
per row.
When I delete a row in TransplantList
, I also want to delete (if it's not NULL) the heartId
associated with it.
I tried adding this to my context database:
Entity.OnDelete(DeleteBehavior.Cascade);
But that just gives me an error.
Is there anyway to do this?
Thanks!
Entity Framework core cannot cascade delete child data for you if the parent and child tables don't have any relationship and foreign key. So you have to get child data manually before deleting child and parent data.
var heart = context.Hearts.Where(x => x.HeartId == transparent.HeartId).FirstOrDefault();
if (heart != null)
context.Hearts.Remove(heart);
context.Transparents.Remove(transparent);
context.SaveChanges();