1

I am new to Entity Framework. Is it possible to delete an entity from a table directly instead of going and clearing all the many to many connection with other tables?

var artist = _artistDetailsRep.SingleOrDefault(d => d.ArtistID == id);

_artistDetailsRep.Delete(artist);
_artistDetailsRep.SaveChanges();

This code complains because the artist has many to many connections (constraints) to artistTypes. So what works is below

 artist.ArtistTypes.Clear();
_artistDetailsRep.Delete(artist);
_artistDetailsRep.SaveChanges();

I need to explicitly clear all the artisttypes and then delete the artist. Is there a way of doing this automatically? Basically it should delete all the connection by itself instead me going and saying delete those constraints?

May be you can suggest a better approach to these scenarios?

akd
  • 6,538
  • 16
  • 70
  • 112

1 Answers1

2

You can let SQL Server do this for you by using Cascading Deletes. Entity Framework also has support for this by using the WillCascaseOnDelete() method in the Fluent API, see this article for more information. This question also might help you.

Please keep in mind that cascading deletes are pretty dangerous though, one mistake in your code might wipe a complete table in your database.

Community
  • 1
  • 1
Henk Mollema
  • 44,194
  • 12
  • 93
  • 104