Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I delete rows from tables using EF when inside an Asp.Net method?

I have this method:

[Route("Delete")]
public IHttpActionResult Delete()
{

}

What I would like to do is to delete from three tables that are here:

public System.Data.Entity.DbSet<SampleSentence> SampleSentences { get; set; } 
public System.Data.Entity.DbSet<Synonym> Synonyms { get; set; } 
public System.Data.Entity.DbSet<WordForm> WordForms { get; set; } 

Is there a delete function in EF6 that I can use to delete all the rows or should I somehow make a SQL call?

like image 536
Alan2 Avatar asked Jun 06 '16 05:06

Alan2


People also ask

How do I remove all rows from a table in Entity Framework?

There are times when we may need to delete all the records from the table using Entity Framework. One of the commonly used ways is to iterate each row and use the DBSet. Remove() .

How can I delete row data from a table?

Right-click in a table cell, row, or column you want to delete. On the menu, click Delete Cells. To delete one cell, choose Shift cells left or Shift cells up. To delete the row, click Delete entire row.

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 table in EDMX?

In the . edmx, right-click in the area between tables and select Model Browser. It will open a file tree of all the tables contained in your model. Delete every instance of the table you changed in your database.


2 Answers

Assuming you have a DbContext derived class...

using (var transactionScope = new TransactionScope()) {
    try {
        string sql = @"
DELETE SampleSentence 
DELETE Synonym 
DELETE WordForm
";

        int count = myDbContext.Database.ExecuteSqlCommand(sql);
        if(count > 0) 
            transactionScope.Complete();
    } catch(Exception ex) {
        //Logging
    }
}
like image 192
Nkosi Avatar answered Oct 17 '22 04:10

Nkosi


You can use this EntityFramework.Extended library, with it help one can write:

context.SampleSentences.Delete();
context.Synonyms.Delete();
context.WordForms.Delete();
like image 36
Slava Utesinov Avatar answered Oct 17 '22 04:10

Slava Utesinov