6

Is it possible to get LINQ to SQL to delete a record using the PK, without loading the record first? Similar to NHibernate's proxy object functionality?

2 Answers 2

16

You should be able to do it this way:

var person = new Person();
person.ID = someID;

using (var context = new DataContext(connString))
{
    context.Persons.Attach(person, false); //attach is as unmodified
    context.Persons.DeleteOnSubmit(person); //remove it
    context.SubmitChanges(); //submit changes to db
}
Sign up to request clarification or add additional context in comments.

Comments

3

Adding to Joseph's answer:

You may have trouble deleting in this manner if your entity has any fields for which UpdateCheck is set to Always, unless you set such fields as appropriate.

Also, if you are deleting multiple related entities where FK constraints are involved, you may have trouble if the entities are not deleted in the proper sequence (resulting in a constraint violation). To avoid this, set all fields involved in such FKs as appropriate.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.