ASP.NET MVC 框架下的 Code-First 方法






4.94/5 (27投票s)
ASP.NET MVC 框架下的 Code-First 方法
引言
我们都知道数据库是任何应用程序的核心,有时管理它太复杂了,对吧?是的。这就是为什么微软推出了 Entity Framework:它降低了复杂性,让开发人员无需太多数据库知识就能轻松编写出出色的程序。因此,如今大多数微软 .Net 开发人员都使用 .Net Entity Framework 进行数据库操作。
什么是 Entity Framework?
Entity Framework 是一个 对象关系映射器,这意味着它会获取数据库的结构并将其转换为 .Net 框架可以理解的对象。开发人员使用这些对象与数据库进行交互,而不是直接与数据库交互。可以使用 Entity Framework 的功能执行完整的创建、读取、更新和删除 (CRUD) 操作。
它有三种工作流程
-
Code – first(代码优先),
-
Model-first(模型优先)和
-
database first(数据库优先)。
选择和使用正确的方法可以为开发人员节省大量时间和精力,尤其是在处理复杂的数据库设计时。
在本文中,我们将通过一个简单的演示应用程序来演示 Code-first 工作流程。
涵盖内容
- 理解 Code First 工作流程
- 在 MVC 应用程序中演示 Code-first 方法的简单示例。
理解 Code First 工作流程
Code-first 方法是在 Entity Framework 4.1 中引入的,是微软推出的最新工作流程。它允许我们将编码的类转换为数据库应用程序,这意味着 code first 允许我们使用 POCO(简单旧式 CLR 对象)类来定义我们的领域模型,而不是使用基于 XML 的 EDMX 文件,后者与 entity framework 没有依赖关系。我们的模型类成为领域模型,因此我们必须非常谨慎地设计我们的模型类。其余工作将由 entity framework 完成。这就是 code-first 方法的魅力所在,我们的模型类成为 Entity framework 依赖的数据模型。
在 Asp.Net MVC 应用程序中演示 Code-first 方法的简单示例
1) 创建一个名为“CodeFirstModel”的类库项目,并命名解决方案为“CodeFirstDemoApplication”。打开 VS -> 文件 -> 新建项目 -> 类库项目。参见下图。
并创建一个名为“Employee.cs”的新类。项目名称 -> 右键单击 -> 添加 -> 类。
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool IsEmployeeRetired { get; set; }
public string Country { get; set; }
public string Company { get; set; }
}
Code-first 将使用此模型类来定义 entity framework 所依赖的数据模型。它有一个约定(我们将在下一篇文章中进一步讨论),如果找到一个名为 Id 的属性,或者一个名为 类型名称+Id 的属性(即 EmployeeId),该属性将被自动配置为主键,并且非空,同时该键在表中标记为自动递增的标识。如果找不到任何符合此约定的属性,它将在运行时抛出异常,告知没有键(即 EntityType “类名”没有定义键。请为该实体类型定义键)。
2) 创建另一个名为“CodeFirstDataAccess”的类库项目:右键单击项目解决方案 -> 添加 -> 新建项目 -> 类库项目,并从 NuGet 包管理器中 安装 Entity Framework。选择项目 -> 右键单击 -> 管理 NuGet 包 -> 搜索 Entity FrameWork -> 安装。参见下图。
i) 将 entity framework dll 和“CodeFirstModel”的引用添加到当前项目“即 CodeFirstDataAccess”。
ii) 添加一个名为“DemoEntityContext.cs”的类 - 然后实现 DBContext 和 DBSet 来与数据库及其操作进行交互。
public class DemoEntityContext : DbContext
{
public DemoEntityContext() : base("name=DbConnectionString") { }
public DbSet<Employee> Employees { get; set; }
}
这个简单的类代表了我们应用程序的整个数据层。“DBConnectionString”是在 web.config 文件中定义的连接字符串名称(稍后讨论)。
DBContext – 简单来说,这个类负责与数据库交互,并在运行时管理实体对象,包括用数据库中的数据填充对象、更改跟踪以及将数据持久化到数据库。
DBSet - 这个类表示一个实体集,用于创建、读取、更新和删除操作。
3) 添加一个名为“CodeFirstWebApp”的空 MVC Web 应用程序,该应用程序将使用上述数据层进行数据库操作。右键单击项目解决方案 -> 添加 -> 新建项目 -> ASP.NET MVC4 Web 应用程序。参见截图
i) 添加 HomeController.cs 控制器,Index.cshtml(razor 视图),然后添加一个部分视图(查看部分视图详细信息)来显示员工记录“_EmployeeDetailView.cshtml”,以及一个名为“EmployeeModel.cs”的模型类,并包含 jquery 文件。
a) Index.cshtml 中的内容
@{
ViewBag.Title = "Index";
}
<!DOCTYPE html>
<meta name="viewport" content="width=device- <title>Index</title>
<body>
<input type="button" value="InsertRecord" id="btnInsertRecord"/>
<input type="button" value="DisplayRecords" id="btnDisplay"/>
<div id="divPartial">
</div>
</body>
<script src="~/Content/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(function () {
$('#btnInsertRecord').click(function (data) {
$.post("@Url.Action("InsertEmployeeDetail", "Home")", function (data) {
if (data) {
alert('Successfuly inserted!!');
} else {
alert('An error occured!');
}
});
});
$('#btnDisplay').click(function (data) {
$.post("@Url.Action("GetEmployeeDetails", "Home")", function (data) {
if (data) {
$('#divPartial').append(data);
} else {
alert('An error occured!');
}
});
});
});
</script>
</html>
两个按钮用于插入和显示信息,它们会触发 HomeController.cs 类中的操作方法。
b) HomeController.cs 中的内容
public ActionResult Index()
{
try
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DemoEntityContext>());
return View();
}
catch (Exception)
{
throw;
}
}
DropCreateDatabaseIfModelChanges:如果任何模型类发生更改并且我们想更新它,那么我们需要实现这个类。它将删除并重新创建数据库。更改完成后可以删除它。
DropCreateDatabaseAlways:每次初始化上下文时,它都会删除并重新创建数据库。
public ActionResult InsertEmployeeDetail() { try { for (int counter = 0; counter < 5; counter++) { var emp = new Employee() { Name = "Eemployee " + counter, Company = "Mindfire Solutions " + counter, Description = "Software Engineer", IsEmployeeRetired = false, Country = "India", }; using (var context = new DemoEntityContext()) { context.Employees.Add(emp); context.SaveChanges(); } } } catch (Exception) { throw; } return Json(true); }
上面的操作代码将向 Employee 表插入一些演示记录
public ActionResult GetEmployeeDetails() { var model = new List<EmployeeModel>(); try { using (var context = new DemoEntityContext()) { var value = context.Employees.ToList(); foreach (var employee in value) { var empModel = new EmployeeModel(); empModel.EmployeeName = employee.Name; empModel.Company = employee.Company; empModel.Country = employee.Country; empModel.Description = employee.Description; empModel.IsEmployeeRetired = employee.IsEmployeeRetired? "Yes": "No"; model.Add(empModel); } } } catch (Exception) { throw; } return PartialView("_EmployeeDetailView", model); }
此方法将简单地获取员工详细信息并将其传递给部分视图
c) 部分视图“_EmployeeDetailView.cshtml”
@model List<CodeFirstWebApp.Models.EmployeeModel>
@{
Layout = null;
}
<h1>Employee Informations</h1>
@if (Model != null)
{
<div>
<table cellspacing="0"width="50%" border="1">
<thead>
<tr>
<th>
Employee Name
</th>
<th>
Company Name
</th>
<th>
Department
</th>
<th>
Employee Retired
</th>
<th>
Country
</th>
</tr>
</thead>
<tbody>
@foreach (var employee in Model)
{
<tr>
<td align="center">
@employee.EmployeeName
</td>
<td align="center">
@employee.Company
</td>
<td align="center">
@employee.Description
</td>
<td align="center">
@employee.IsEmployeeRetired
</td>
<td align="center">
@employee.Country
</td>
</tr>
}
</tbody>
</table>
</div>
}
d) EmployeeModel.cs:- 用于表示员工详细信息的模型类
public class EmployeeModel
{
public string EmployeeName { get; set; }
public string Description { get; set; }
public string Country { get; set; }
public string IsEmployeeRetired { get; set; }
public string Company { get; set; }
}
II) 添加对 entity framework、模型类项目“CodeFirstModel”和“CodeFirstDataAccess”的引用。
现在我们的演示项目差不多完成了。参见下方截图了解解决方案的最终结构。
III) 并将项目设置为“设置为启动项目”。
但是问题是,我们的数据库在哪里? Code-first 的默认约定(表示如果没有设置任何配置)会在本地 SQL Server Express 实例 (localhost\SQLEXPRESS) 中查找一个与上下文类的完全限定名称(ProjectName.COntextClassName)匹配的数据库,即 (CodeFirstDataAccess.DemoEntityContext)。如果找不到,Code First 会创建数据库,然后使用它通过约定发现的模型来构建数据库的表和列。参见下图 - 图片本身描述了 code-first 方法中数据库的初始化过程。
在我们的演示中,我们将通过配置文件来定位数据库位置 - 因为这种方法在我们要将应用程序部署到不同环境时非常有用。在这种情况下,Code First 约定会确切地知道为特定上下文使用哪个数据库,方法是使用 DbContext 构造函数或应用程序的配置文件。
Web.config
<connectionStrings> <add name="DbConnectionString" providerName="System.Data.SqlClient" connectionString="Server=.; Database=EmployeeDB; Trusted_Connection=true" /> </connectionStrings>
DbConnectionString - 上面使用的连接字符串名称。使用这个,Code-first 将在 本地 SQL Server 中创建一个名为“EmployeeDB”的数据库。
哇,现在我们准备构建我们的第一个 code-first 演示应用程序了。
按 F5 运行应用程序:观察
1) 将显示一个索引页面,然后按“InsertRecord”按钮。现在检查本地数据库,您将找到一个名为“EmployeeDB”的数据库,其中有一个名为“Employee”的表和一些记录。
2) 按“DisplayRecord”按钮,嗯,这就是我们的最终结果。