MVC学习笔记二:实现简单的增删改查

来源:互联网 发布:淘宝如何改实名认证 编辑:程序博客网 时间:2024/05/21 19:49

前面做了些准备工作,现在就是要利用EF实现对数据库表的增删改查了偷笑


打开项目,鼠标右击Controllers文件夹,将控制器名称改为:IphonesController 点击新建.

完成后会看到在Controllers文件夹下面多出了IphonesController.cs文件,打开文件,看到下面代码:

    public class IphonesController : Controller    {        //        // GET: /Iphones/        public ActionResult Index()        {            return View();        }    }
右击View新建视图,创建强类型视图,会发现在下拉列表中没有Iphones模型选择,编译也根本编译不通,这里比较让人费解,也许是要手动去创建Model,但是我太懒了,并没有这么做。


打开Apples.edmx文件,鼠标右击空白处,选择属性,代码生成策略改成“默认值”:


设置完成后,再用鼠标点击Apples.edmx下的Apples.Designer.cs文件,会发现里面自动生成了分部类ApplesContainer,但是这又带来一个问题,

在Apples.edmx文件下的Apples.Context.tt下的Apples.Context.cs里也有个分部类ApplesContainer,它们继承的不是同一个类...敲打如下:

    public partial class ApplesContainer : DbContext    {        public ApplesContainer()            : base("name=ApplesContainer")        {        }            protected override void OnModelCreating(DbModelBuilder modelBuilder)        {            throw new UnintentionalCodeFirstException();        }        }
    public partial class ApplesContainer : ObjectContext    {        #region 构造函数            /// <summary>        /// 请使用应用程序配置文件的“ApplesContainer”部分中的连接字符串初始化新 ApplesContainer 对象。        /// </summary>        public ApplesContainer() : base("name=ApplesContainer", "ApplesContainer")        {            this.ContextOptions.LazyLoadingEnabled = true;            OnContextCreated();        }
我采用了两种方式解决:

方法一:使用ObjectContext

删除Apples.Context.tt文件。重新编译项目,这时候再去右击控制器下的Index方法,新建视图,选择强类型视图,这时候就有Iphones了。支架模板选择List。


注意为什么要找Iphones这个类,其实这个类就是对应我们的数据库中的Iphones表,而它的属性对应的就是表中的列。这就是EF的一个映射模式。

在IphonesController.cs文件添加对ApplesContainer类的引用:

using FirstMvcWithEF.Entities;
修改Index方法如下:

        public ActionResult Index()        {            ApplesContainer db = new ApplesContainer();            return View(db.Iphones);            //或者            //ViewData.Model = db.Iphones;            //return  View();        }

编译运行,在浏览器的地址栏后面添加/iphones,看到:



到这里查询算是成功了。

接下来看插入操作:实现点击上面的Create New连接向数据库中插入数据。

在Index方法下面,新建一个Create方法:

        public ActionResult Create()        {            return View();        }
同样的方式新建视图,支架模板选择Create,直接运行:



这时候如果点击Create按钮去post这个表单,是没有任何意义的,因为IphonesController控制器根本就没有一个post型的方法让表单去执行;

下面添加post方式的action方法:

        [HttpPost]        public ActionResult Create(Iphones iphone)        {            ApplesContainer db=new ApplesContainer();            db.Iphones.AddObject(iphone);            db.SaveChanges();            return View("Index",db.Iphones);        }

编译执行:


点击Create,可以看到数据插入成功!



接下来介绍修改数据:实现点击Edit能够修改数据。

同样新建一个Edit方法:

        public ActionResult Edit(int id)        {            ApplesContainer db = new ApplesContainer();            var iphone = db.Iphones.FirstOrDefault(a => a.ID == id);            ViewData.Model = iphone;            return View();        }
新建对应的视图,注意支架模板选择Edit,省的自己去编辑视图。

再新建一个post方式的方法,用于提交修改执行的方法:

        [HttpPost]        public ActionResult Edit(Iphones iphone)        {            ApplesContainer db = new ApplesContainer();            db.Iphones.Attach(iphone);            db.ObjectStateManager.ChangeObjectState(iphone, EntityState.Modified);            db.SaveChanges();            return View("Index",db.Iphones);        }
编译运行:点击某一个Edit,修改其数据:


点击Save:


修改已经成功。

接下来介绍删除:实现点击Delete删除数据。

同样,新建一个Delete方法及对应的post方法(默认Get不用加[HttpGet])]:

      public ActionResult Delete(int id)        {            ApplesContainer db = new ApplesContainer();            var iphone = db.Iphones.FirstOrDefault(a => a.ID == id);            ViewData.Model = iphone;            return View();        }        [HttpPost]        public ActionResult Delete(Iphones iphone)        {            ApplesContainer db = new ApplesContainer();            db.Iphones.Attach(iphone);            db.ObjectStateManager.ChangeObjectState(iphone, EntityState.Deleted);            db.SaveChanges();            return View("Index", db.Iphones);        }

编译运行:点击某一个Delete,


点击Delete:



确实删除成功!

到目前为止,方法一:使用ObjectContext进行增删改查,已经完成。

-----------------------------------------------------------------------------------------------------------------------------------------------

接下来使用第二种方式。

方法二:使用DbContext进行增删改查.

由于前面,直接把Apples.edmx下的文件给删除了,现在需要删除Apples.edmx,重新新建该文件。

新建时“选择从数据库生成”,由于我们的Web.config中已经配置过了,所以这里直接跳出了之前配置过的连接名称ApplesContainer.


选择之前生成的Ipones表:



创建完成后,打开下图两个红色直线标注的文件:


会发现第一个文件,相比之前的而言,多出了最后一行自动属性:

    public partial class mydbEntities : DbContext    {        public mydbEntities()            : base("name=mydbEntities")        {        }            protected override void OnModelCreating(DbModelBuilder modelBuilder)        {            throw new UnintentionalCodeFirstException();        }            public DbSet<Iphones> Iphones { get; set; }    }

而第二个文件Iphones.cs是直接多出来的,它描述了Iphons表的结构:

    public partial class Iphones    {        public int ID { get; set; }        public string type { get; set; }        public string color { get; set; }        public decimal price { get; set; }    }
这时候打开IphonesController控制器,会发现原先些的代码出现了错误,原先的ApplesContainer都需要替换成mydbEntities,

还有,原先的AddObject方法,ObjectStateManager都不能用了。

db.Iphones.AddObject(iphone);

换成

db.Iphones.Add(iphone);
的形式

,将

db.ObjectStateManager.ChangeObjectState(iphone, EntityState.Modified);
换成形式:

db.Entry(iphone).State=EntityState.Modified;
删除同样。Details就暂时不加了,跟前面删除Get形式一样。

编译运行:

增删改查都一样正常。