I am relatively new to EF (V6) and am thoroughly confused by the myriad aspects of cascade delete and the settings affecting it. My main aim is to do all the required settings in code, and not to have to go to SQL Svr Mgmt Studio (SSMS) to tweak something; this is code-first, and I want the end-user to be able to create the database. My model, for tests, is simple:
Customer
Supplier
Address
A Customer has many Addresses
A Supplier has many Addresses
No Address is shared between Customer and Supplier
If I delete either a Customer or Supplier, the Address must be deleted at the same time
I prefer not to have any navigation properties in Address, but rather to keep Address just that, with no reference to its consumers. It is a general-purpose class after all.
Unless anyone can advise a better way, I have in fact made Address a base class of CAddress and SAddress, both of which classes could contain properties specific to Customer and Supplier addresses respectively. I end up with an Address table with a Discriminator column and an xx_id column for each Address type. It all sounds very simple, and it is surprising how difficult deleting has proved to be.
I now need to know how to reliably implement cascade delete. At present, the only way that I can get this to work is to load all Address children into memory (via .Include()) and also have a cascade delete rule set in SSMS. But (a) how, at any point, can I know if all children are in memory? and (b) I can't manually change the db design when the application is deployed. I also found, at one point, that cascade deletion obviously worked in SSMS (delete parent and children are deleted too) but that this did not work from Remove()/SaveChanges() unless all children were loaded into memory. I had thought that cascade delete via an FK constraint obviated the need to load children in memory - yes? no?
Can someone please explain how to set up cascade deletion for my simple model, given so many possible players in the scenario: WillCascadeOnDelete, use of virtual, type of collection used, loading into memory (or not), lazy/eager loading, setting FK constraints manually/at runtime, use of fluent API and/or annotations, Remove(), DeleteObject(), removing children manually via foreach and the Remove()-ing parent... and so on.
My anticipation of useful replies has been eagerly loaded! Note: this differs from this question in that it refers to 1-to-many, no nav. props. and numerous other aspects of EF settings.
you have no navigational properties Customer and Supplier and you don't want them on Address entity then EF Code First will generate a nullable FK on the Address table because it thinks Address can exist w'out related Customer or Supplier hence will not activate the cascade deletion on those FKs. You must add this fluent config: modelBuilder.Entity