Entity Framework - ObjectContext.DeleteObject() when related entities are orphaned
I have two entities in a many to one relationship. Widget (1) <--> (*) Users.
If for some strange reason there has been a Widget deleted in the database, where there may not be a foreign key or other referential constraint that would prevent a Users from existing if there was not a corresponding Widget, I cannot use EF to ObjectContext.DeleteObject(). The message is
System.Data.UpdateException: Entities in '<Users>' participate in the '<UsersWidgets>' relationship. 0 related 'Widgets' were found. 1 'Widget' is expected. at System.Data.Mapping.Update.Internal.UpdateTranslator.RelationshipConstraintValidator.ValidateConstraints()
Is there a recommended way to deal with this in code?
You should modify your Entity Data Model (EDM) to conform to the rules expressed in the database schema.
If there aren't any referencial integrity constraints between the User and Widgets tables in the database and the foreign key column in User is nullable, then the association between their corresponding entities in the EDM should have a multiplicity of 0..1:* (zero or one-to-many).
Right now it is probably set to 1:* (one-to-many) which is causing the validation error, since according to that a User is always expected to have exactly one associated Widget.