MVC學習筆記(三)—用EF向數據庫中添加數據


1.在EFDemo文件夾中添加Controllers文件夾(用的是上一篇MVC學習筆記(二)—用EF創建數據庫中的項目)

2.在Controllers文件夾下添加一個空的控制器(StudentsController)

3.在StudentsController中的Index方法中添加視圖

4.在EFDemo中添加EFCore的引用

5.向數據庫添加數據

 5.1 方法一,StudentsController代碼如下:

 1 using System;  2 using System.Web.Mvc;  3 using EFCore;  4 
 5 namespace EFDemo.Controllers  6 {  7     public class StudentsController : Controller  8  {  9         // GET: Students
10         public ActionResult Index() 11  { 12             using (EFContextDB db = new EFContextDB()) 13  { 14                 Students s = new Students(); 15                 s.Name = "張三"; 16                 s.School = "中山大學"; 17                 s.ID = Guid.NewGuid(); 18                 s.CreatedTime = DateTime.Now; 19  db.Students.Add(s); 20                 int result = db.SaveChanges(); 21                 return View(); 22  } 23  } 24  } 25 }

但是顯示12行報錯

解決方法:在EFDemo中安裝EntityFramework

5.2 方法二:

using System; using System.Web.Mvc; using EFCore; namespace EFDemo.Controllers { public class StudentsController : Controller { private EFContextDB db = new EFContextDB(); // GET: Students
        public ActionResult Index() { Students s = new Students(); s.Name = "李四"; s.School = "廈門大學"; s.ID = Guid.NewGuid(); s.CreatedTime = DateTime.Now; db.Students.Add(s); int result = db.SaveChanges(); return View(); } } }

 (其實5.1和5.2本質上是一樣的)

6.題外話:如何修改默認路由

 6.1 打開RouteConfig.cs文件

 

      改成如下即可:

     

 

寫在后面的話:一枚起步很晚的程序猿,現在正在努力把原來落下的知識補回來。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM