frosty

Deleting records in a one to Many Relationship Linq To Sql

Rate this Entry
Today I inherited some code and in some scenarios records would not delete. The standard Row Not Found or has changes exception was thrown which seemed bogus.

After fighting around with the syntax, the following syntax finally worked.

Code:
using (SMARTLynxDataContext _dc = CreateDataContext())
                {
                    var removeRecipient = _dc.MailRecipients.Single(m => m.ID == id);
                    _dc.MailRecipientsAlertAlarms.DeleteAllOnSubmit(removeRecipient.MailRecipientsAlertAlarms);
                    _dc.MailRecipients.DeleteOnSubmit(removeRecipient);
                    _dc.SubmitChanges();
                }
MailRecipientsAlertAlarms has a many to one relationship to MailRecipients. In the code above, we get the MailRecipient record we want to delete. We submit all it's MailRecipientAlarms to be deleted and then we submit the MailRecipient record to be deleted and call SubmitChanges().
Tags: ling to sql
Categories
Linq To Sql

Comments