你的位置:首页 > ASP.net教程

[ASP.net教程]1.创建一个EF实体数据模型


1.The Contoso University sample web application demonstrates how to create ASP.NET MVC 5 applications using the Entity Framework 6 and Visual Studio 2013. This tutorial uses the Code First workflow. For information about how to choose between Code First, Database First, and Model First, see Entity Framework Development Workflows.(这个网站的例子,向我们展示了,怎样使用EF6和VS2013来创建ASP.NET MVC5应用程序。这个系列的课程使用了Code First工作流。要了解怎么在Code First,Database First 和Model First之间进行选择,请看链接这篇文章。)

2.The sample application is a web site for a fictional Contoso University. It includes functionality such as student admission, course creation, and instructor assignments. This tutorial series explains how to build the Contoso University sample application. You can download the completed application.

(这个示例程序是为Contoso University虚构的一个网站。网站的功能包含:招生模块,课程的创建模块,布置作业模块,这个系列的课程将带你创建这个网站,你可以通过这个链接下载完整的网站源代码。)

3.课程中用到的软件环境:

  • Visual Studio 2013
  • .NET 4.5
  • Entity Framework 6 (EntityFramework 6.1.0 NuGet package)
  • Windows Azure SDK 2.2 (可选)

The Contoso University Web Application

The application you'll be building in these tutorials is a simple university web site.(在这个系列课程中,你将要创建的是一个大学的简单web网站)

Users can view and update student, course, and instructor information. Here are a few of the screens you'll create.(你可以浏览,更新学生、课程信息,和老师信息,这里的一些页面,将是你将来要创建的。)

 

The UI style of this site has been kept close to what's generated by the built-in templates, so that the tutorial can focus mainly on how to use the Entity Framework.(这个网站的界面样式,使用的是默认提供的模板样式,所以这个课程将会把主要的精力放在,怎样去使用EF上面。PS:后面我会自己使用EasyUI和Bootstrap自己把界面美化一下。)

Create an MVC Web Application

Open Visual Studio and create a new C# Web project named "ContosoUniversity".(打开VS,创建一个新的web项目,取名为ContosoUniversity)

In the New ASP.NET Project dialog box select the MVC template. (在新的ASP.NET项目中,选择MVC模板)

If the Host in the cloud check box in the Microsoft Azure section is selected, clear it.(如果在云中托管被选中了,请取消勾选

Click Change Authentication.(点击更改身份验证)

In the Change Authentication dialog box, select No Authentication, and then click OK. For this tutorial you won't be requiring users to log on or restricting access based on who's logged on.(在更改身份验证的对话框中,选择无身份验证,然后点击确定。这个系列的课程,你不会被要求,需要让用户来登录,或者限制用户登录)

Back in the New ASP.NET Project dialog box, click OK to create the project. (返回到新建ASP.NET项目的界面,点击确定,创建新项目)

Set Up the Site Style(设置站点的样式)

A few simple changes will set up the site menu, layout, and home page.(我们会对菜单,样式,和主页做一些细微的改变)

Open Views\Shared\_Layout.cshtml, and make the following changes:(打开Views\Shared\_Layout.cshtml文件,做如下改变

  • Change each occurrence of "My ASP.NET Application" and "Application name" to "Contoso University".(把每个”My ASP.NET Application“和“Application name”改成“Contoso University”)PS:这里可以随便改,你想取什么名字都行,我取武汉大学。
  • Add menu entries for Students, Courses, Instructors, and Departments, and delete the Contact entry.(为学生,课程,老师,部门添加菜单选项链接,并且删除联系方式链接)

The changes are highlighted.(这些改变都做了高亮显示:)

 1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 5   <meta charset="utf-8" /> 6   <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7   <title>@ViewBag.Title - WuHan University</title> 8   @Styles.Render("~/Content/css") 9   @Scripts.Render("~/bundles/modernizr")10 </head>11 <body>12   <div class="navbar navbar-inverse navbar-fixed-top">13     <div class="container">14       <div class="navbar-header">15         <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">16           <span class="icon-bar"></span>17           <span class="icon-bar"></span>18           <span class="icon-bar"></span>19         </button>20         @Html.ActionLink("Wuhan University", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })21       </div>22       <div class="navbar-collapse collapse">23         <ul class="nav navbar-nav">24           <li>@Html.ActionLink("主页", "Index", "Home")</li>25           <li>@Html.ActionLink("关于", "About", "Home")</li>26           <li>@Html.ActionLink("学生", "Index", "Student")</li>27           <li>@Html.ActionLink("课程", "Index", "Course")</li>28           <li>@Html.ActionLink("教师", "Index", "Instructor")</li>29           <li>@Html.ActionLink("部门", "Index", "Department")</li>30         </ul>31       </div>32     </div>33   </div>34   <div class="container body-content">35     @RenderBody()36     <hr />37     <footer>38       <p>&copy; @DateTime.Now.Year - Wuhan University</p>39     </footer>40   </div>41 42   @Scripts.Render("~/bundles/jquery")43   @Scripts.Render("~/bundles/bootstrap")44   @RenderSection("scripts", required: false)45 </body>46 </html>

 In Views\Home\Index.cshtml, replace the contents of the file with the following code to replace the text about ASP.NET and MVC with text about this application:(在Views\Home\Index.cshtml中,用下面的代码,来代替它

 1 @{ 2   ViewBag.Title = "主页"; 3 } 4  5 <div class="jumbotron"> 6   <h1>WuHan University</h1> 7 </div> 8 <div class="row"> 9   <div class="col-md-4">10     <h2>Welcome to WuHan University</h2>11     <p>12       WuHan University is a sample application that13       demonstrates how to use Entity Framework 6 in an14       ASP.NET MVC 5 web application.15     </p>16   </div>17   <div class="col-md-4">18     <h2>Build it from scratch</h2>19     <p>You can build the application by following the steps in the tutorial series on the ASP.NET site.</p>20     <p><a class="btn btn-default" href="http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/">See the tutorial &raquo;</a></p>21   </div>22   <div class="col-md-4">23     <h2>Download it</h2>24     <p>You can download the completed project from the Microsoft Code Gallery.</p>25     <p><a class="btn btn-default" href="http://code.msdn.microsoft.com/ASPNET-MVC-Application-b01a9fe8">Download &raquo;</a></p>26   </div>27 </div>

Press CTRL+F5 to run the site. You see the home page with the main menu.(按一下CTRL+F5,来运行项目,你可以看到:)

Install Entity Framework 6(安装EF6)

From the Tools menu click NuGet Package Manager and then click Package Manager Console.(点击工具-->NuGet程序包管理器--->程序包管理器控制台)

In the Package Manager Console window enter the following command:(在程序包管理器控制台窗口里,输入下面的指令:)

Install-Package EntityFramework

The image shows 6.0.0 being installed, but NuGet will install the latest version of Entity Framework (excluding pre-release versions), which as of the most recent update to the tutorial is 6.1.1.

This step is one of a few steps that this tutorial has you do manually, but which could have been done automatically by the ASP.NET MVC scaffolding feature. You're doing them manually so that you can see the steps required to use the Entity Framework. You'll use scaffolding later to create the MVC controller and views. An alternative is to let scaffolding automatically install the EF NuGet package, create the database context class, and create the connection string. When you're ready to do it that way, all you have to do is skip those steps and scaffold your MVC controller after you create your entity classes. (PS这两段话,无关精要,我就不翻译了。)

Create the Data Model(创建数据模型)

Next you'll create entity classes for the Contoso University application. You'll start with the following three entities:

(接下来,你将要开始这个应用程序,你会以下面三个实体开始这个程序:)

There's a one-to-many relationship between Student and Enrollment entities, and there's a one-to-many relationship between Course and Enrollment entities. In other words, a student can be enrolled in any number of courses, and a course can have any number of students enrolled in it.

In the following sections you'll create a class for each one of these entities.(在Student和Enrollment实体是一对多的关系,Course 和Enrollment 也是一对多的关系,换句话说,一个学生能够选修很多课程,并且一个课程可以有很多学生选修)

In the Models folder, create a class file named Student.cs and replace the template code with the following code:

(在Model文件下,添加一个类,命名为Student.cs,并用下面的代码代替模板的代码:)

 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5  6 namespace ContosoUniversity.Models 7 { 8   public class Student 9   {10     public int ID { get; set; }11     public string LastName { get; set; }12     public string FirstMidName { get; set; }13     public DateTime EnrollmentDate { get; set; }14     public virtual ICollection<Enrollment> Enrollments { get; set; }15   }16 }

The ID property will become the primary key column of the database table that corresponds to this class. By default, the Entity Framework interprets a property that's named ID or classnameID as the primary key.(ID属性将会变成对应实体数据表的主键,默认,EF会将命名为ID或者ClassnameID作为主键)

The Enrollments property is a navigation property. Navigation properties hold other entities that are related to this entity. In this case, the Enrollments property of a Student entity will hold all of the Enrollment entities that are related to that Student entity. In other words, if a given Student row in the database has two related Enrollmentrows (rows that contain that student's primary key value in their StudentID foreign key column), that Studententity's Enrollments navigation property will contain those two Enrollment entities.

(Enrollments是一个导航属性,导航属性包含其他和这个有关的实体,在这个例子中Student实体的导航属性Enrollments,会包含所有的Enrollment实体,并关联到Student实体上。换句话说,如果数据库中的Student行,有两个关联的外键属性)

Navigation properties are typically defined as virtual so that they can take advantage of certain Entity Framework functionality such as lazy loading. (Lazy loading will be explained later, in the Reading Related Data tutorial later in this series.)

(导航属性,特别的定义成virtual,所以可以利用EF的懒加载(懒加载在后面会解释到,在这个系列的课程的后面)

If a navigation property can hold multiple entities (as in many-to-many or one-to-many relationships), its type must be a list in which entries can be added, deleted, and updated, such as ICollection.

(如果导航属性能够包含很多实体(比如多对多,或者一对多),它的类型必须是一个List。可以增删改,例如ICollection)

In the Models folder, create Enrollment.cs and replace the existing code with the following code:

(在Model文件夹下面,添加一个Enrollment类,用下面的代码,代替已经存在的代码:

 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5  6 namespace ContosoUniversity.Models 7 { 8   public enum Grade 9   {10     A, B, C, D, F11   }12  public class Enrollment13   {14     public int EnrollmentID { get; set; }15     public int CourseID { get; set; }16     public int StudentID { get; set; }17     public Grade? Grade { get; set; }18     public virtual Course Course { get; set; }19     public virtual Student Student { get; set; }20     21   }22 }

The EnrollmentID property will be the primary key; this entity uses the classnameID pattern instead of ID by itself as you saw in the Student entity. Ordinarily you would choose one pattern and use it throughout your data model. Here, the variation illustrates that you can use either pattern. In a later tutorial, you'll you'll see how using ID withoutclassname makes it easier to implement inheritance in the data model.

(EnrollmentID属性将会是主键,这个实体使用了classnameID模型代替了ID模型,就像你在Student模型中看到的那样。通常你会选择一个模型,然后在数据模型的,全篇的始终都使用它,你可以使用ID和classnameID模型中的任何一个,在后面的课程中,你将会看到使用ID,在数据模型中,会很容易的实现继承。

The Grade property is an enum. The question mark after the Grade type declaration indicates that the Gradeproperty is nullable. A grade that's null is different from a zero grade — null means a grade isn't known or hasn't been assigned yet.

(这个Grade属性是一个枚举,Grade后面的一个问号,表明这个属性是可以为空的,null不同于0,null表示不知道,或者还没有被分配。)

The StudentID property is a foreign key, and the corresponding navigation property is Student. An Enrollmententity is associated with one Student entity, so the property can only hold a single Student entity (unlike theStudent.Enrollments navigation property you saw earlier, which can hold multiple Enrollment entities).

(StudentID属性是一个外键,并且导航属性是Student,一个Enrollmententity关联一个Student,所以这个属性只能够包含单个Student实体(不像你前面看到的Student的Enrollments导航属性,它可以包含多个Enrollment 实体。))

The CourseID property is a foreign key, and the corresponding navigation property is Course. An Enrollmententity is associated with one Course entity.

(课程号是一个外键,导航属性是课程,一个Enrollmententity关联一个课程实体。)

Entity Framework interprets a property as a foreign key property if it's named <navigation property name><primary key property name> (for example, StudentID for the Student navigation property since the Student entity's primary key is ID). Foreign key properties can also be named the same simply <primary key property name> (for example, CourseID since the Course entity's primary key is CourseID).

(EF会解释一个属性为外键,如果其命名成了导航属性,例如StudentID在Student中是导航属性,因为Stduent实体,已经有主键了,是ID),外键属性同样能够,被命名为这个主键属性名称,例如CourseID是Course的主键,因为CourseID是Course实体的主键。

 

。。。。本节未完,明天下班继续更新。。。