I have two entities in a many to one relationship. Widget (1) <--> (*) Users.
If for some strange reason there has been a Widget deleted i开发者_开发百科n 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?
Thanks!
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.
Related resources:
- Association End Multiplicity (Entity Data Model)
This Exception usually occurs, if you have an FK on Users to Widgets, which is NOT nullable in the DB. So the first thing you should check is, if the FK is defined as nullable on Users. Which Database do you use? I am only aware with MSSQL Server 2008. If so check which properties are set on the relation in the database. You can define an UPDATE and DELETE action on a relation. If you dont want the user to be deleted when the Widget is deleted you should check if cascade delete is disabled. There is also an option to set the Widget on the User to null.
精彩评论