How do I delete a record using Linq to SQL using only the primary key, without having to retrieve the existing record from the database?
Asked
Active
Viewed 3,487 times
9

Brian Tompsett - 汤莱恩
- 5,753
- 72
- 57
- 129

Jeremy
- 44,950
- 68
- 206
- 332
-
Don't have VS to test this at the moment but wouldn't it be something like this: DataContext.Widgets.Delete(new {id = 123}) – nathanchere Mar 08 '10 at 05:37
-
FerretallicA - Nope, I would have figured that out if it was the case. :) – Jeremy Mar 16 '10 at 15:08
2 Answers
4
You should be able to create an instance of the object with the appropriate FK and then Attach() it to the context, Delete() it and then SubmitChanges() which will perform a delete without performing a sql select.
var foo1 = new Foo {Id = 1};
db.Foos.Attach(foo1);
db.Foos.Remove(foo1);
db.SubmitChanges();

bkaid
- 51,465
- 22
- 112
- 128
4
Linq to SQL: Delete an entity using Primary Key only - Omar AL ...

ratty
- 13,216
- 29
- 75
- 108
-
+1 yup basically you need straight SQL for this, Linq-to-SQL doesn't support it natively.... – marc_s Mar 08 '10 at 05:53