MVC3学习 三 EF删除

删除代码:

 public ActionResult Del(int id)
        {
            try
            {
                BlogArticle modelDel = new BlogArticle() { AId = id };
                db.BlogArticles.Attach(modelDel);
                db.BlogArticles.DeleteObject(modelDel);
                db.SaveChanges();
                return RedirectToAction("Index","Home");
            }
            catch (Exception ex)
            {

                return Content("删除失败" + ex.ToString());
            }


        }

前台代码:

  <script type="text/javascript">
    function del(id)
    {
        if (confirm("确定要删除么?")) {
            window.location="Home/del/"+id
        }
    }
    </script>

 <a href="javascript:del(@a.AId)">删除</a>

这里需要注意的是,当要删除某个对象时,一定要先将删除的对象添加到EF管理容器中,因为db.BlogArticles.DeleteObject(modelDel);这句只是将对象标记为删除,并不能添加到EF容器。

 

posted @ 2015-04-01 09:50  8932809  阅读(167)  评论(0编辑  收藏  举报