我有这个方法:
[Route("Delete")]
public IHttpActionResult Delete()
{
}
我想要做的是从这里的三个表中删除:
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; }
EF6中是否有删除功能可用于删除所有行,还是应该以某种方式进行SQL调用?
答案 0 :(得分:2)
假设你有一个DbContext派生类......
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
}
}
答案 1 :(得分:2)
你可以使用这个EntityFramework.Extended library来帮助人们写一下:
context.SampleSentences.Delete();
context.Synonyms.Delete();
context.WordForms.Delete();
答案 2 :(得分:1)
我刚刚在stackoverflow上找到了
db.ProRel.RemoveRange(db.ProRel.Where(c => c.ProjectId == Project_id));
How to delete multiple records with Entity Framework ASP.Net MVC 5?
但我使用此方法删除行
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";
}
对于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();
}