ASP.Net MVC与SQL Server数据库操作

在本教程之前,创建的所有ASP.NET MVC应用程序中,我们一直在将来自控制器的硬编码数据传递给视图模板。 但是,构建真正的Web应用程序,可能需要使用真实的数据库。 在本章中,我们将学习如何使用数据库引擎来存储和检索应用程序所需的数据。

要存储和检索数据,我们将使用Entity框架的.NET Framework数据访问技术来定义和使用模型。

Entity框架(EF)支持Code First技术,该技术允许通过编写简单的类来创建模型对象,然后从类中随时创建数据库,从而实现非常干净和快速的开发流程。

下面来看一个简单的例子,我们将在这个例子中添加Entity框架的支持来访问数据库。

第1步 - 创建一个项目:MVCDatabaseAccess,如下所示 -

要安装Entity Framework框架,右键单击项目,然后选择管理NuGet程序包 ,在弹出的界面中搜索:Entity framework,如下图所示 -

选择Entity framework,然后点击“Install”按钮。它将打开预览对话框 -

接受安装协议,如下图所示 -

Entity framework框架安装成功,会看到下面的截图中所示的绿色“勾”的图标。如下图所示 -

添加DBContext

我们需要向Employee模型添加另一个类,该类将与Entity Framework进行通信,以使用以下代码检索和保存数据。

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

using System.Web;
namespace MVCDatabaseAccess.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文件中的<configuration>标记下为数据库指定连接字符串。

 <connectionStrings>
    <add name = "EmpDBContext" connectionString = "Data Source=MY-PC;Initial Catalog=testdb;Integrated Security=True" providerName = "System.Data.SqlClient"/>
  </connectionStrings>

实际上不需要添加EmpDBContext连接字符串。如果不指定连接字符串,则Entity Framework将使用DbContext类的标准名称在用户目录中创建localDB数据库。 对于这个示例,我们不会添加连接字符串来简化。

现在需要更新EmployeeController.cs文件,以便可以从数据库中保存和检索数据,而不是使用硬编码的数据。

首先,添加创建一个私有的EmpDBContext类对象,然后更新IndexCreateEdit动作方法,如下面的代码所示。参考以下代码 -

using MVCDatabaseAccess.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCDatabaseAccess.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:61868/Employee运行这个应用程序。将看到以下输出。

正如所看到的,这个视图上没有数据,但是程序已经自动创建了一个表:Employee,这是因为我们还没有在数据库表中添加任何记录。

进入SQL Server对象资源管理器,会看到数据库使用与我们在DBContext类中创建的相同的名称 - Employee

展开这个数据库,会看到它有一个包含Employee模型类中的所有字段的表。

要查看此表中的数据,请右键单击Employees表并选择查看数据。应该会看到目前没有数据记录。我们直接在数据库的Employee表中添加一些记录,如下图所示 -

刷新浏览器,应该会看到数据现在已经更新到了视图中了。如下图所示 -

点击“Create New” 链接,从浏览器中添加一条记录,它将显示创建视图。在下面的字段中添加一些数据。

点击Create按钮,它会更新索引视图以及添加这个新的记录到数据库。

现在打开SQL Server对象资源管理器并刷新数据库。右键单击Employees表并选择查看数据菜单选项。应该就会看到该记录被添加到数据库中了。


上一篇: ASP.Net MVC模型绑定 下一篇: ASP.Net MVC验证