C# – ADO.NET Entity Framework: How to get auto cascading deletions

ado.netcdatabaseentity-framework

I am using the Ado.Net Entity Framework with ASP.NET MVC.

In my MSSQL 2008 Database I have for example the following simplified tables and relations:

 (Song) 1--* (Version) 1 -- 1 (VersionInfo)

Is it possible to automatically have the linked Versions and their VersionInfo's deleted when I delete a Song?

Currently I am using something like the following code, which is a lot of manual work, since some tables have up to 8 relations and those relations have subrelations too sometimes:

  db = new Database() //Entities
  Song song = db.Song.First();

  Song.Version.Load();

  foreach(Version version in Song.Version.ToList())
  {
       //Remove Song-Version Reference.
       song.Version.Remove(version);


       //Get The VersionInfo so we can delete it after we deleted the Version object.
       version.VersionInfoReference.Load();
       VersionInfo versionInfo = version.VersionInfo;

       //Now we can delete the Version Object.
       db.DeleteObject(version);
       //Now we can also delete the versionInfo, since the reference is gone.
       db.DeleteObject(versionInfo);

  }

  db.DeleteObject(song);

There must be an easier way to get cascading deletions. I already tried setting the relationship setting in MSSQL to Cascade when Deleting, but it didn't do a thing… Did I miss something there?

Anyway, how do other people solve this problem?

Best Answer

You should not be doing this in the Entity Framework. All popular relational databases support ON CASCADE DELETE on foreign keys which is a lot more efficient as well. I suggest you just go with that.

It appears in your case you may have to cascade deletes in song to version and deletes in version to version info. Just load up the table designer in SQL Manager and you should see the relevant options under relationships.