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文件

 

      改成如下即可:

     

写在后面的话:一枚起步很晚的程序猿,现在正在努力把原来落下的知识补回来。

猜你喜欢

转载自www.cnblogs.com/jas0203/p/9475902.html
今日推荐