zoukankan      html  css  js  c++  java
  • MVC3学习:基于ObjectContext的数据增删改查操作

    数据库里面的表格,映射为对应的实体类。实体类的编写,可以自己手动编写,也可以使用工具或插件自动生成。在MVC3里面,我们可以使用VS的POCO插件自动生成实体类。如下图:

    关于POCO插件的安装与使用,相关文章比较多,本文不再详细讲述,本文主要讲解一下使用POCO生成的实体类,对应的增删改查方法。

    假设有一个存放新闻的表格为News,则对应的实体类名也为News,其中主键为Nid.

    一、增加记录

           [HttpPost]
            public ActionResult Create(News n)
            {
                if (ModelState.IsValid)
                {
                    db.News.AddObject(n);
                    db.SaveChanges();
                    return RedirectToAction("index");
                }
                else
                    return View(n);
            }

    二、删除记录

       [HttpPost]
            public ActionResult Delete(int id)
            {
                try
                {
                    News n = db.News.Where(c => c.Nid == id).Single();
                    db.News.DeleteObject(n);
                    db.SaveChanges();
                    return RedirectToAction("index");
                }
                catch
                {
    
                    return View();
                }
            }

    三、修改记录

      [HttpPost]
            public ActionResult Edit(News n)
            {
                if (ModelState.IsValid)
                {
                    db.News.Attach(n);
                    db.ObjectStateManager.ChangeObjectState(n, System.Data.EntityState.Modified);
                    db.SaveChanges();
                    return RedirectToAction("index");
                }
                else
                    return View(n);
            }

    四、查询记录

    public ActionResult Index()
            {
                return View(db.News.ToList());
            }

    如果是带条件的查询,则可以写为

     public ActionResult Index(int id)
            {
                return View(db.News.Where(c=>c.Nid==id).Single());
            }
  • 相关阅读:
    [GL]行星运行1
    一个图的带权邻接表存储结构的应用
    [GDAL]3.影像金字塔构建
    [GDAL]1.GDAL1.8.1编译与第一个程序
    [GDAL]2.读取栅格和矢量数据
    C#迭代器
    GoogleEarth缓存机制探索
    AE开发三维的不足!
    [GDAL]4.影像的读取和显示
    [STL学习]1.概述
  • 原文地址:https://www.cnblogs.com/denny402/p/3197011.html
Copyright © 2011-2022 走看看