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?
If you want the department to remain and to be able to do this, you will need to alter the foreign key to include ON DELETE SET NULL. Otherwise, you will have to drop the constraint, perform the delete, and recreate the constraint.
To drop a primary key from a table, use an ALTER TABLE clause with the name of the table (in our example, product ) followed by the clause DROP PRIMARY KEY . Since a table can have only one primary key, you don't need to specify the primary key column(s).
To successfully change or delete a row in a foreign key constraint, you must first either delete the foreign key data in the foreign key table or change the foreign key data in the foreign key table, which links the foreign key to different primary key data.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With