JMon
JMon

Reputation: 3447

Cannot delete in EF4

I am trying to delete an "AttendeeEvent" from the database with EF4, however I am getting the following error:-

The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

My code is as follows :-

        public void UnRegisterCurrentUserForEvent(int eventId)
    {
        Attendee attendee = GetOrCreateAttendeeForCurrentUser();
        AttendeeEvent av = attendee.AttendeeEvents.SingleOrDefault(x => x.EventID == eventId);

        if(av != null)
        {
            attendee.AttendeeEvents.Remove(av);
        }

        this.ObjectContext.SaveChanges();
    }

I tried to change the End 2 On Delete from the properties in the .edmx however when I set to cascade, I am getting an error:-

Error 1 Error 132: cannot have operation specified since its multiplicity is ''. Operations cannot be specified on ends with multiplicity ''

Can you guys help me out

Thanks for your help and time

Upvotes: 2

Views: 1678

Answers (1)

Ronald Wildenberg
Ronald Wildenberg

Reputation: 32094

You are only removing the AttendeeEvent from the collection of attendee events for an Attendee. So suppose you have an attendee A and event AV and you remove AV from A. What should happen inside the database? You haven't actually removed AV. You've only said that A should no longer be related to AV. So inside your database, the foreign key from AV to A is set to NULL, which is not allowed by your database model.

The fix is simple: replace the line where you remove the event from the attendee with the following line:

this.ObjectContext.AttendeeEvents.DeleteObject(av);

Upvotes: 2

Related Questions