views:

594

answers:

1

I have in my Database a Contact table and a Phone table, in the phone table there is column "ContactId" with a key that references the phone to the contact.

In the key options in the server I set its delete option to 'Cascade'.

Now when I attempt to delete a contact using the context:

Dim contact As Contact 'The contact I want to delete.
Dim context As New Entities 'The ObjectContext.
context.DeleteObject(contact)
context.SaveChanges()

The above statement throws an UpdateException letting me know that the Contact still have Phone records whose ContactId col is set to its ID.

Now I know that I can do it manually and delete first all the related phones then remove the contact, but I am looking for a more efficient way, I want all this should be done automatically.

Any suggestions and practices are welcomed.

Thanks.

A: 

You don't need to manually delete the Phone records first, but you do need to load them. Once the records are loaded, the Entity Framework will figure out what to do.

Also, this blog post has a method for deleting objects in the entity framework without retrieving them first. The issue of deleting objects with references to related objects is discussed. It might help you get your head around what is going on under the hood.

Craig Stuntz
Hi Craig!The link you provided was very helpful!However, it didn't answer my question, or at least I didn't understand it.I loaded the contact + the phones and when I delete I still get the exception.Could you please post a brief example?Thank you very much!
Shimmy
It really is that simple: contract.Phones.Load(). If that doesn't work, something is not right, and I would ensure that your mapping is correct.
Craig Stuntz

related questions