简体   繁体   中英

Delete a LINQ to SQL record without loading it first

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?

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
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM