65.9K
CodeProject 正在变化。 阅读更多。
Home

在 MVC 4 中使用 Entity Framework 5 完成 CRUD 操作,无需编写一行代码

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.84/5 (92投票s)

2013年12月12日

CPOL

4分钟阅读

viewsIcon

476401

downloadIcon

11292

使用 Entity Framework 5 在 MVC 4 中完成 CRUD 操作,无需编写一行代码。

引言

在本文中,我将介绍如何在 MVC4 应用程序中使用 Entity Framework 5 执行基本的 CRUD 操作,而无需编写一行代码。EF 和 MVC 已经发展到我们无需付出额外努力的程度。

I) MVC

模型:整个应用程序运行的业务实体。许多应用程序使用持久化存储机制(如数据库)来存储数据。MVC 没有具体提及数据访问层,因为它被理解为由模型封装。

视图 (View):将模型呈现为交互形式的用户界面。

控制器 (Controller):处理来自视图的请求并更新导致模型状态更改的模型。

要在 .NET 中实现 MVC,我们主要需要三个类(ViewControllerModel)。

II) Entity Framework

让我们看一下 Microsoft 提供的 Entity Framework 的标准定义

“Microsoft ADO.NET Entity Framework 是一个对象/关系映射 (ORM) 框架,它使开发人员能够将关系数据作为领域特定的对象进行处理,从而消除了开发人员通常需要编写的大部分数据访问样板代码。使用 Entity Framework,开发人员可以使用 LINQ 发出查询,然后以强类型对象的形式检索和操作数据。Entity Framework 的 ORM 实现提供了诸如更改跟踪、标识解析、延迟加载和查询翻译等服务,使开发人员能够专注于其应用程序特定的业务逻辑,而不是数据访问基础。”

简单来说,Entity Framework 是一个对象/关系映射 (ORM) 框架。它是 ADO.NET 的增强,是 ADO.NET 的上层,为开发人员提供了一种自动化的机制来访问和存储数据库中的数据。

希望这能让你对 ORM 和 EntityFramework 有个初步的了解。

III) MVC 应用程序

步骤 1:创建一个名为 LearningKO 的数据库,并在其中添加一个名为 student 的表,表脚本如下

USE [LearningKO]
GO
/****** Object:  Table [dbo].[Student]    Script Date: 12/04/2013 23:58:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Student](
	[StudentId] [nvarchar](10) NOT NULL,
	[FirstName] [nvarchar](50) NULL,
	[LastName] [nvarchar](50) NULL,
	[Age] [int] NULL,
	[Gender] [nvarchar](50) NULL,
	[Batch] [nvarchar](50) NULL,
	[Address] [nvarchar](50) NULL,
	[Class] [nvarchar](50) NULL,
	[School] [nvarchar](50) NULL,
	[Domicile] [nvarchar](50) NULL,
 CONSTRAINT [PK_Student] PRIMARY KEY CLUSTERED 
(
	[StudentId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, _
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
INSERT [dbo].[Student] ([StudentId], [FirstName], [LastName], [Age], _
[Gender], [Batch], [Address], [Class], [School], [Domicile]) _
VALUES (N'1', N'Akhil', N'Mittal', 28, N'Male', N'2006', N'Noida', N'Tenth', N'LFS', N'Delhi')
INSERT [dbo].[Student] ([StudentId], [FirstName], [LastName], [Age], _
[Gender], [Batch], [Address], [Class], [School], [Domicile]) _
VALUES (N'2', N'Parveen', N'Arora', 25, N'Male', N'2007', N'Noida', N'8th', N'DPS', N'Delhi')
INSERT [dbo].[Student] ([StudentId], [FirstName], [LastName], [Age], _
[Gender], [Batch], [Address], [Class], [School], [Domicile]) _
VALUES (N'3', N'Neeraj', N'Kumar', 38, N'Male', _
N'2011', N'Noida', N'10th', N'MIT', N'Outside Delhi')
INSERT [dbo].[Student] ([StudentId], [FirstName], [LastName], [Age], _
[Gender], [Batch], [Address], [Class], [School], [Domicile]) _
VALUES (N'4', N'Ekta', N'Mittal', 25, N'Female', N'2005', N' Noida', N'12th', N'LFS', N'Delhi')

步骤 2:打开你的 Visual Studio(Visual Studio 版本应大于或等于 12),然后添加一个 MVC Internet 应用程序。

我将其命名为“KnockoutWithMVC4”。

步骤 3:你将在 Controller 文件夹中获得一个结构完整的 MVC 应用程序,其中包含默认的 Home controller。默认情况下,entity framework 作为包下载到应用程序文件夹中,但如果不是,你可以通过右键单击项目,选择“管理 NuGet 程序包”,然后搜索并安装 Entity Framework 来添加 entity framework 包。

步骤 4:右键单击项目文件,选择“添加新项”,然后添加 ADO.NET 实体数据模型,按照如下所示的向导步骤进行操作

从数据库生成模型,选择你的服务器和 LearningKO 数据库名称,连接字符串将自动添加到你的 Web.Config 中,将该连接字符串命名为 LearningKOEntities

选择要添加到模型中的表。在本例中,是 Student 表。

步骤 5:现在向 Controller 文件夹添加一个新的控制器,右键单击 controller 文件夹并添加一个名为 Student 的控制器。由于我们已经创建了 Datamodel,我们可以选择由所选 Entity Framework Datamodel 创建 CRUD 操作的选项。

  • 将控制器命名为 StudentController
  • 在“脚手架选项”中,选择“使用 Entity Framework 的带读/写操作和视图的 MVC 控制器”。
  • Model 类选择为 Student,它位于我们的解决方案中。
  • 将数据上下文类选择为 LearningKOEntities,这是我们在添加 EF 数据模型时添加到我们解决方案中的。
  • 选择 Razor 作为视图的渲染引擎。
  • 单击“高级选项”,选择“布局或母版页”,然后从共享文件夹中选择 _Layout.cshtml

步骤 6:我们看到我们的 student 控制器已准备好所有 CRUD 操作操作,如下所示

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
	
namespace KnockoutWithMVC4.Controllers
{
    public class StudentController : Controller
    {
        private LearningKOEntities db = new LearningKOEntities();
	
        //
        // GET: /Student/
	
        public ActionResult Index()
        {
            return View(db.Students.ToList());
        }
	
        //
        // GET: /Student/Details/5
	
        public ActionResult Details(string id = null)
        {
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }
	
        //
        // GET: /Student/Create

        public ActionResult Create()
        {
            return View();
        }
	
        //
        // POST: /Student/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Student student)
        {
            if (ModelState.IsValid)
            {
                db.Students.Add(student);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
	
            return View(student);
        }
	
        //
        // GET: /Student/Edit/5
	
        public ActionResult Edit(string id = null)
        {
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }
	
        //
        // POST: /Student/Edit/5
	
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Student student)
        {
            if (ModelState.IsValid)
            {
                db.Entry(student).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(student);
        }
	
        //
        // GET: /Student/Delete/5

        public ActionResult Delete(string id = null)
        {
            Student student = db.Students.Find(id);
            if (student == null)
            {
	                return HttpNotFound();
            }
            return View(student);
        }
	
        //
        // POST: /Student/Delete/5
	
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(string id)
        {
            Student student = db.Students.Find(id);
            db.Students.Remove(student);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
	
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}

步骤 7:打开 App_Start 文件夹,并将控制器名称从 Home 更改为 Student

代码将变为如下

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Student", 
        action = "Index", id = UrlParameter.Optional }
    );
}

步骤 8:现在按 F5 运行应用程序,你将看到我们在创建时添加到 Student 表中的所有学生列表。由于 CRUD 操作是自动编写的,我们有用于显示列表以及其他编辑、删除和创建操作的操作结果。请注意,所有操作的视图都创建在 Views 文件夹下的 Student 文件夹名中。

现在你可以在此列表上执行所有操作。

由于我没有对模型提供任何验证检查,也没有创建已存在的学生 ID,代码可能会出错,因此当发现 ID 已存在时,我将调用 Edit Action 来创建。

现在创建新学生。

我们看到学生已成功创建并添加到列表中。

在数据库中。

同样对于编辑

更改任何字段并按保存。更改将反映在列表和数据库中

用于删除

学生已删除。

并在数据库中

到目前为止还没有编写一行代码。

结论

在本教程中,我们学习了如何设置 MVC 和 Entity Framework 5 的环境,并在不编写一行代码的情况下对 Student 模型执行 CRUD 操作。你可以通过添加多个控制器、模型和视图来扩展应用程序。

注意:本文中的部分图片来自 Google 搜索。

你可以在 csharppulse.blogspot.in 上关注我的文章。

祝您编码愉快!

© . All rights reserved.