5

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?

Nkosi
  • 235,767
  • 35
  • 427
  • 472
Alan2
  • 23,493
  • 79
  • 256
  • 450
  • Project the DbSets into a List and then Enumerate each to `DbSet.Remove`. You can then call `SaveChanges` on the `DbContext`. If not you can always Use `DbContext.Database.ExecuteSqlCommand` – Nkosi Jun 06 '16 at 05:38
  • @Nkosi - Would that not make many calls to the database? Can I do it with somehow sending SQL direct to the database? – Alan2 Jun 06 '16 at 05:41
  • Yes, the second part of my comment allows for SQL direct on the database – Nkosi Jun 06 '16 at 05:41
  • With the first suggestion it will only execute one call when you invoke SaveChanges – Nkosi Jun 06 '16 at 05:44

3 Answers3

2

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
    }
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • @Nikosi - Does that call to the database return a code to indicate if it worked or not? Just wondering if I should put all this in a try catch to check for possible exceptions. Thanks. – Alan2 Jun 06 '16 at 05:51
  • it's normally the count of how many row were affected by the command. You can wrap it in a transaction and try catch in case of error so you can roll back if needed. – Nkosi Jun 06 '16 at 05:52
2

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

context.SampleSentences.Delete();
context.Synonyms.Delete();
context.WordForms.Delete();
Slava Utesinov
  • 13,410
  • 2
  • 19
  • 26
1

I just found on stackoverflow

db.ProRel.RemoveRange(db.ProRel.Where(c => c.ProjectId == Project_id));

How to delete multiple records with Entity Framework ASP.Net MVC 5?

But I use this method to delete a row

var Cert = (from cert in db.TblCompCertUploads where cert.CertID == ID select cert).FirstOrDefault();
if (Cert != null)
{
    db.TblCompCertUploads.DeleteObject(Cert);
    db.SaveChanges();
    ViewBag.Msg = "Deleted Successfully";
}

For Mulitple Rows

List<tbl_CompCertificate> tbp = db.tbl_CompCertificate.Where(t => t.CompCer_CompId == CompId).ToList();
foreach (tbl_CompCertificate t in tbp)
{
    db.tbl_CompCertificate.DeleteObject(t);
    db.SaveChanges();
}
Community
  • 1
  • 1
Arun Prasad E S
  • 9,489
  • 8
  • 74
  • 87