开发者

Entity Framework: delete record with its sub-records

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

How can I delete a specific record with all 开发者_JAVA技巧its children (n levels deep)?

Using Entity Framework 3.5.


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


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


@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,

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜