LINQ Deletes
The following example deletes a record for a given Id.
Entities context = new Entities();
var query = from Accounts in context.Accounts
where Accounts.Id == "anId"
select Accounts;
context.DeleteObject(query.FirstOrDefault());
try {
context.SaveChanges();
} catch (Exception e) {
Console.Write(e.Message);
}
This next example deletes a group of records whose Industry value equals "Floppy Disks". Do note that LINQ only
performs one delete operation per record at a time, as specified by a record's Id. Also note that because of this, LINQ
incurs a performance penalty as it opens a fresh connection with the data source everytime it deletes a record.
Entities context = new Entities();
var query = from Accounts in context.Accounts
where Accounts.Industry == "Floppy Disks"
select Accounts;
foreach (var result in query) {
var delete = from Accounts in context.Accounts
where Accounts.Id == result.Id
select Accounts;
context.DeleteObject(delete.FirstOrDefault());
}
try {
context.SaveChanges();
} catch (Exception e) {
Console.Write(e.Message);
}