views:

79

answers:

1

I'm trying to wrap my head around Entity Framework 4. This is probably an easy question ;)

I have the following entities: Article, Comment and Picture. Articles have a one-to-many association with Comments. Articles have also a many-to-many relationship with Pictures.

My question is what would be the proper approach to deleting an Article that has Comments and Pictures. Mind you there are the following scenarios:

  1. Article has neither Comments, nor Pictures associated.
  2. Article has Comments but no Pictures.
  3. Article has Comments and Pictures that aren't shared with other Articles.
  4. Article has Comments and Pictures that are shared with other Articles. (Only Pictures can be shared, the comments are exclusive).

I've already noticed that just executing:

_db.DeleteObject(art);

does not work and I have to first delete the Comments and the Pictures in advance. Also if the Picture is shared, I only wanted to delete the association to the particular Article not all the associations.

I'm sure there is easier way to achieve this - is there like a "cascade delete" that would take care of this scenario?

I appreciate your help!

A: 

Yes, there is on delete cascade but not in the entity framework. However you can just put them on your foreign keys to your many-to-many link tables.

klausbyskov
There is `on delete cascade` in Entity Framework: http://blogs.msdn.com/alexj/archive/2009/08/19/tip-33-how-cascade-delete-really-works-in-ef.aspx http://codepolice.net/2008/12/16/cascade-delete-in-entity-framework/
LukLed
@LukeLed: Quote the link: "If you add an Cascade delete rule to the model, you MUST have a corresponding DELETE rule in the database.", but good point still.
klausbyskov
That's because the only way it could possibly work without a corresponding rule in the DB is running a big possibly faulty (consider uncommitted data) `DELETE FROM ... WHERE ID IN SELECT ....` statement, which seems like an odd approach when every RDBMS has a better solution built in.
Craig Stuntz
Thank you very much for your comments and suggestions!
Michal Rogozinski