Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete using only the primary key?

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?

like image 908
Jeremy Avatar asked Mar 08 '10 05:03

Jeremy


People also ask

Can we delete primary key without deleting foreign key?

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.

How can I delete one primary key in MySql?

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).

Can we delete constraints in primary or foreign key?

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.


1 Answers

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();
like image 191
bkaid Avatar answered Nov 12 '22 20:11

bkaid