Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 441
Neil Barnwell Avatar asked Aug 21 '09 14:08

Neil Barnwell


People also ask

How do I delete a record in LINQ query?

Proper way to delete record in LINQ to Entities My delete function worked when I did the following:... using (var ctx = new MyEntity()) { var x = (from y in ctx. Employees orderby y. EmployeeId descending select y).

How do I delete a record in entity Framework?

Delete a Record In Connected Scenario, you can use the Remove or RemoveRange method to mark the record as Deleted . In Disconnected Scenario, you can attach it to the context and set its state as Deleted . Calling SaveChanges will send the delete query to the database.

How do I delete a record in .NET core?

Deleting an entity is done using the Remove or RemoveRange method of the DbSet. Alternatively, you can also set the entity state as Deleted . We can delete records either in connected or disconnected Scenarios. We will also look at how to remove multiple records from the database using the RemoveRange method.


1 Answers

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
}
like image 128
Joseph Avatar answered Oct 05 '22 17:10

Joseph