ASP.NET MVC - 数据库

在本教程中创建的所有ASP.NET MVC应用程序中,我们一直将硬编码数据从控制器传递到View模板.但是,为了构建真正的Web应用程序,您可能希望使用真正的数据库.在本章中,我们将了解如何使用数据库引擎来存储和检索应用程序所需的数据.

要存储和检索数据,我们将使用.NET Framework数据访问技术称为实体框架,用于定义和使用模型.

实体框架(EF)支持Code First技术,它允许您通过编写简单的类来创建模型对象.然后,数据库将从您的类中动态创建,这将实现非常干净和快速的开发工作流程.

让我们看一个简单的示例,我们将在其中添加对Entity的支持我们的例子中的框架.

第1步 : 要安装Entity Framework,请右键单击您的项目,然后选择NuGet Package Manager → 管理解决方案的NuGet包...

安装实体框架

它将打开 NuGet包管理器.在搜索框中搜索实体框架.

搜索实体框架

选择实体框架,然后单击"安装"按钮.它将打开预览对话框.

选择实体框架

单击确定继续.

许可接受

单击'我接受'按钮开始安装.

我接受按钮

安装实体框架后,您将在外部窗口中看到消息,如上面的屏幕截图所示.

添加DBContext

我们需要添加另一个Employee Model类,它将与Entity Framework通信,使用以下代码检索和保存数据.

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;

using System.Web;

namespace MVCSimpleApp.Models{
   public class Employee{
      public int ID { get; set; }
      public string Name { get; set; }
      public DateTime JoiningDate { get; set; }
      public int Age { get; set; }
   }
	
   public class EmpDBContext : DbContext{
      public EmpDBContext()
      { }
      public DbSet<Employee> Employees { get; set; }
   }
}

如上所示, EmpDBContext 派生自一个名为

连接字符串

我们需要在< configuration>下指定连接字符串Web.config文件中我们数据库的标记.

<connectionStrings>
   <add name = "EmpDBContext" connectionString = "Data
   Source = (LocalDb)\v14.0;AttachDbFilename = |DataDirectory|\EmpDB.mdf;Initial
   Catalog = EmployeeDB;Integrated Security = SSPI;"
   providerName = "System.Data.SqlClient"/>
</connectionStrings>

您实际上不需要添加EmpDBContext连接字符串.如果未指定连接字符串,Entity Framework将使用DbContext类的完全限定名称在用户的目录中创建localDB数据库.对于本演示,我们不会添加连接字符串以简化操作.

现在我们需要更新EmployeeController.cs文件,以便我们可以实际保存和检索数据库中的数据使用硬编码数据.

首先,我们添加创建一个私有的EmpDBContext类对象,然后更新索引,创建和编辑操作方法,如下面的代码所示.

using MVCSimpleApp.Models;
using System.Linq;
using System.Web.Mvc;

namespace MVCSimpleApp.Controllers {
   public class EmployeeController : Controller{
      private EmpDBContext db = new EmpDBContext();
      // GET: Employee
		
      public ActionResult Index(){
         var employees = from e in db.Employees
         orderby e.ID
         select e;
         return View(employees);
      }
		
      // GET: Employee/Create
      public ActionResult Create(){
         return View();
      }
		
      // POST: Employee/Create
      [HttpPost]
      public ActionResult Create(Employee emp){
         try{
            db.Employees.Add(emp);
            db.SaveChanges();
            return RedirectToAction("Index");
         }catch{
            return View();
         }
      }
		
      // GET: Employee/Edit/5
      public ActionResult Edit(int id){
         var employee = db.Employees.Single(m => m.ID == id);
         return View(employee);
      }
		
      // POST: Employee/Edit/5
      [HttpPost]
      public ActionResult Edit(int id, FormCollection collection){
         try{
            var employee = db.Employees.Single(m => m.ID == id);
            if (TryUpdateModel(employee)){
               //To Do:- database code
               db.SaveChanges();
               return RedirectToAction("Index");
            }
            return View(employee);
         }catch{
            return View();
         }
      }
   }
}

然后我们使用以下网址运行此应用程序 HTTP://本地主机:63004/雇员的.您将看到以下输出.

Name JoiningDate Age

正如您所看到的,视图中没有数据,这是因为我们没有在Visual Studio中创建的数据库中添加任何记录.

让我们转到SQL Server对象资源管理器,您将看到创建的数据库与我们在DBContext类中的名称相同.

DBContext类

让我们展开这个数据库,您将看到它有一个表,其中包含我们在Employee模型类中的所有字段.

员工模型类

要查看此表中的数据,请右键单击Employees表并选择查看数据.

员工表V iew数据

您会看到我们目前没有记录.

No Records Moment

让我们直接在数据库中添加一些记录,如下面的屏幕截图所示.

在数据库中添加记录

刷新浏览器,您将看到数据现在已从数据库更新到视图.

更新后的视图

让我们点击"新建",从浏览器中添加一条记录'链接.它将显示创建视图.

创建视图

让我们看看在以下字段中添加一些数据.

添加一些数据

单击"创建"按钮,它将更新"索引"视图,并将此新记录添加到数据库中.

新记录数据库

现在让我们去SQL Server对象资源管理器并刷新数据库.右键单击Employees表,然后选择View data菜单选项.您将看到该记录已添加到数据库中.

数据库中添加的记录