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

     

          改成如下即可:

         

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

  • 相关阅读:
    Alien Security (BFS+DFS)
    HDU 1495 喝可乐(暴力BFS)
    Tempter of the Bone(奇偶剪枝)の反面教材
    Fire Game (双起点bfs)
    Linux学习
    c# 实现IComparable、IComparer接口、Comparer类的详解
    DataTable 基本转换简单实例
    C#集合
    递归方法
    存储过程生成复杂的随机编号
  • 原文地址:https://www.cnblogs.com/jas0203/p/9475902.html
Copyright © 2020-2023  润新知