ASP.NET MVC - 数据库

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

为了存储和检索数据,我们将使用称为实体框架(Entity Framework)的 .NET Framework 数据访问技术来定义和使用模型。

实体框架(Entity Framework) (EF) 支持代码优先技术,该技术允许您通过编写简单的类来创建模型对象,然后将从您的类动态创建数据库,从而实现非常干净且快速的开发工作流程。

让我们看一个简单的示例,我们将在示例中添加对实体框架(Entity Framework)的支持。

步骤 1 − 要安装实体框架(Entity Framework),请右键单击您的项目并选择 NuGet 包管理器 → 管理解决方案的 NuGet 包...

安装实体框架(Entity Framework)

它将打开NuGet 包管理器。 在搜索框中搜索实体框架(Entity Framework)。

搜索实体框架(Entity Framework)

选择实体框架(Entity Framework)并单击"安装"按钮。 它将打开预览对话框。

选择实体框架(Entity Framework)

单击"确定"继续。

许可证接受

单击"我接受"按钮开始安装。

我接受按钮

安装实体框架(Entity Framework)后,您将在窗口中看到消息,如上面的屏幕截图所示。

添加数据库上下文

我们需要向员工模型添加另一个类,该类将使用以下代码与实体框架(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 派生自称为 DbContext 的 EF 类。 在此类中,我们有一个名为 DbSet 的属性,它基本上代表您要查询和保存的实体。

连接字符串

我们需要在下指定连接字符串 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 类对象,然后更新 Index、Create 和 Edit 操作方法,如以下代码所示。


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();

         }

      }

   }

}

然后我们使用以下 URL http://localhost:63004/Employee 运行此应用程序。 您将看到以下输出。

Name JoiningDate Age

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

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

DBContext 类

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

员工模型类

要查看此表中的数据,请右键单击"员工"表并选择"查看数据"。

员工表视图数据

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

无记录

让我们直接在数据库中添加一些记录,如下图所示。

在数据库中添加记录

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

更新视图

让我们通过单击"新建"链接从浏览器添加一条记录。 它将显示"创建"视图。

创建视图

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

添加一些数据

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

新记录数据库

现在让我们进入 SQL Server 对象资源管理器并刷新数据库。 右键单击"员工"表并选择"查看数据"菜单选项。 您将看到该记录已添加到数据库中。

数据库中添加的记录

关于我们 | 隐私条款 | 学习路线
返回顶部