views:

75

answers:

3

I have a table with 3 columns: ID, Name, ParentID.

How can I delete a specific record with all its children (n levels deep)?

Using Entity Framework 3.5.

A: 

In SQL Set the database relationship to cascade delete and then rebuild your EDMX.

Martin Beeby
Cascade? But cascade works with multiple tables relationship, I got only 1 table.
shivesh
+1  A: 

@Shivesh - I suggest you to use a little method implemented with recursion to delete a son, and all of its parents. Thus, if a parent have parents you can delete them also, and so on.

An alternative could be implementing a stored procedure, the corresponding link in EntityFramework, and pretty do the same.

Hope that helps,

Ramon Araujo
+1 probably easiest to wrap this up in a stored proc and just call it from EF.
marc_s
Well I know it can be done using SP, but I asked about EF.
shivesh
A: 

That the table is self referencing is application logic, it is not expressed in the SQL definition, and therefore is not understood by EF.

To delete these records through EF you need to write a routine that starts at the top and loads all the sub items. Then mark all these items as deleted, then call save changes.

To delete an item:

context.DeleteObject(item);
context.SaveChanges();
Shiraz Bhaiji
what do you mean mark all items as deleted?
shivesh
@shivesh, I have updated the answer
Shiraz Bhaiji
I know how to delete itemsI asked what is: "mark all these items as deleted".Should I add new column to flag for deletion?
shivesh
No new column, what I meant is that DeleteObject marks the object as deleted, SaveChanges then does the actual deletion.
Shiraz Bhaiji
oh! ok. I plan to to load all items and then use recursion to mark the items that need to be deleted.
shivesh