SkyeBoniwell
SkyeBoniwell

Reputation: 7092

How to delete related data with no foreign key using Entity Framework Core

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!

Upvotes: 0

Views: 1534

Answers (2)

atiyar
atiyar

Reputation: 8305

The Cascade operation is not a part of Entity Framework. It only defines it. The operation itself is performed solely by the database server based on the foreign-key relationship. If your database doesn't define that relationship, there's nothing Entity Framework can do.

As for -

How to delete related data with no foreign key using Entity Framework Core

check if a related entity exist. If it does, delete it -

var transplant = await context.Transplants.FindAsync(id);
if(transplant != null)
{
    // check if heartId column on Transplant has a non-null value
    if(transplant.HeartId != null)
    {
        // query the Heart entity with heartId
        Heart heart = await context.Hearts.FirstOrDefaultAsync(p => p.HeartId == transplant.HeartId);

        // if a Heart entity is found, Delete it
        if(heart != null)
            context.Hearts.Remove(heart);
    }

    context.Transplants.Remove(transplant); 

    await context.SaveChangesAsync();
}

Upvotes: 2

Asherguru
Asherguru

Reputation: 1741

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();

Upvotes: 2

Related Questions