It’s not generally correct that you can “remove an item from a database” with both methods. To be precise it is like so:
-
ObjectContext.DeleteObject(entity)marks the entity asDeletedin the context. (It’sEntityStateisDeletedafter that.) If you callSaveChangesafterwards EF sends a SQLDELETEstatement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown. -
EntityCollection.Remove(childEntity)marks the relationship between parent andchildEntityasDeleted. If thechildEntityitself is deleted from the database and what exactly happens when you callSaveChangesdepends on the kind of relationship between the two:-
If the relationship is optional, i.e. the foreign key that refers from the child to the parent in the database allows
NULLvalues, this foreign will be set to null and if you callSaveChangesthisNULLvalue for thechildEntitywill be written to the database (i.e. the relationship between the two is removed). This happens with a SQLUPDATEstatement. NoDELETEstatement occurs. -
If the relationship is required (the FK doesn’t allow
NULLvalues) and the relationship is not identifying (which means that the foreign key is not part of the child’s (composite) primary key) you have to either add the child to another parent or you have to explicitly delete the child (withDeleteObjectthen). If you don’t do any of these a referential constraint is violated and EF will throw an exception when you callSaveChanges– the infamous “The relationship could not be changed because one or more of the foreign-key properties is non-nullable” exception or similar. -
If the relationship is identifying (it’s necessarily required then because any part of the primary key cannot be
NULL) EF will mark thechildEntityasDeletedas well. If you callSaveChangesa SQLDELETEstatement will be sent to the database. If no other referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.
-
I am actually a bit confused about the Remarks section on the MSDN page you have linked because it says: “If the relationship has a referential integrity constraint, calling the Remove method on a dependent object marks both the relationship and the dependent object for deletion.“. This seems unprecise or even wrong to me because all three cases above have a “referential integrity constraint” but only in the last case the child is in fact deleted. (Unless they mean with “dependent object” an object that participates in an identifying relationship which would be an unusual terminology though.)