EF7 更新:
using (var db = new BloggingContext())
{
var blog = db.Blogs.First(p => p.Id == Id);
db.Remove(blog);
db.SaveChanges();
}
2015 年 5 月更新:检查msdn和示例上的更新文档。使用 EF6 删除实体的示例代码:
public async Task<ActionResult> Delete(Department department)
{
try
{
db.Entry(department).State = EntityState.Deleted;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
catch (DbUpdateConcurrencyException)
{
return RedirectToAction("Delete", new { concurrencyError = true, id = department.DepartmentID });
}
catch (DataException /* dex */)
{
//Log the error (uncomment dex variable name after DataException and add a line here to write a log.
ModelState.AddModelError(string.Empty, "Unable to delete. Try again, and if the problem persists contact your system administrator.");
return View(department);
}
}
如果您知道 ID 并且没有加载实体,最有效的方法是创建假实体并将其删除
var p = new Program { Id = myId }
dbContext.Program.Remove(p)
But this won't work if you really have several records with the same id and you need to use name
field as well to select right one.
Also your last example should be
var pg = dbContext.Program.First(p => p.Id == Id && p.Name == FName);
dbContext.Program.Remove(pg);