标签:
本系列教程是微软asp.net网站上的教程翻译,原文地址:http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application 欢迎大家批评指正,共同进步。
vs2013
.NET4.5
EF6(有关ef的版本,根据项目安装版本而定)
在Views\Shared\_Layout.cshtml中做如下修改:
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 - ContosoUniversity</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("Contosouniversity", "Index", "Home", null, 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("联系方式", "Contact", "Home")</li> 27 <li>@Html.ActionLink("Students", "Index", "Student")</li> 28 <li>@Html.ActionLink("Courses", "Index", "Course")</li> 29 <li>@Html.ActionLink("Instructors", "Index", "Instructor")</li> 30 <li>@Html.ActionLink("Departments", "Index", "Department")</li> 31 </ul> 32 </div> 33 </div> 34 </div> 35 <div class="container body-content"> 36 @RenderBody() 37 <hr /> 38 <footer> 39 <p>© @DateTime.Now.Year - Contosouniversity</p> 40 </footer> 41 </div> 42 43 @Scripts.Render("~/bundles/jquery") 44 @Scripts.Render("~/bundles/bootstrap") 45 @RenderSection("scripts", required: false) 46 </body> 47 </html>
工具->库程序包管理器->程序包管理器控制台
在控制台中输入:Install-Package EntityFramework
在Model文件夹中添加类文件:Student,Enrollment,Course
1 using System; 2 using System.Collections.Generic; 3 4 namespace ContosoUniversity.Models 5 { 6 public class Student 7 { 8 public int ID { get; set; } 9 public string LastName { get; set; } 10 public string FirstMidName { get; set; } 11 public DateTime EnrollmentDate { get; set; } 12 public virtual ICollection<Enrollment> Enrollments { get; set; } 13 } 14 }
Enrollment实体:
1 namespace ContosoUniversity.Models 2 { 3 public class Enrollment 4 { 5 public int EnrollmentID { get; set; } 6 public int StudentID { get; set; } 7 public int CourseID { get; set; } 8 public Grade? Grade { get; set; } 9 public virtual Course Course { get; set; } 10 public virtual Student Student { get; set; } 11 } 12 public enum Grade 13 { 14 A, B, C, D, F 15 } 16 }
Course实体:
1 using System.Collections.Generic; 2 using System.ComponentModel.DataAnnotations.Schema; 3 4 namespace ContosoUniversity.Models 5 { 6 public class Course 7 { 8 [DatabaseGenerated(DatabaseGeneratedOption.None)] 9 public int CourseID { get; set; } 10 public string Title { get; set; } 11 public int Credits { get; set; } 12 public virtual ICollection<Enrollment> Enrollments { get; set; } 13 } 14 }
因为之后我们要编辑Course实体,ID不需要数据库自动生成,所以使用DatabaseGenerated属性。
项目中添加DAL文件夹,在DAL文件夹中添加SchoolContext类文件。代码如下
1 using ContosoUniversity.Models; 2 using System.Data.Entity; 3 using System.Data.Entity.ModelConfiguration.Conventions; 4 5 namespace ContosoUniversity.DAL 6 { 7 public class SchoolContext : DbContext 8 { 9 /// <summary> 10 /// 指定连接字符串,名称为SchoolContext 11 /// 如果此处不指定连接字符串名称。那么ef会默认将此类名称作为连接字符串名称,即SchoolContext 12 /// </summary> 13 public SchoolContext() 14 : base("SchoolContext") 15 { } 16 public DbSet<Student> Students { get; set; } 17 public DbSet<Course> Courses { get; set; } 18 public DbSet<Enrollment> Enrollments { get; set; } 19 /// <summary> 20 /// 指定单一表名称,如果不添加此方法,那么数据库中出现的表名称将会为复数(Students,Courses,Enrollments) 21 /// </summary> 22 /// <param name="modelBuilder"></param> 23 protected override void OnModelCreating(DbModelBuilder modelBuilder) 24 { 25 modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); 26 } 27 } 28 }
在DAL文件夹中创建SchoolInitailizer.cs文件,代码如下:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using ContosoUniversity.Models;
namespace ContosoUniversity.DAL
{
public class SchoolInitailizer:DropCreateDatabaseIfModelChanges<SchoolContext>
{
/// <summary>
/// 每组实体后面的SaveChanges方法不是必须的,这么写是当数据写入数据库如果报错方便查找错误。
/// </summary>
/// <param name="context"></param>
protected override void Seed(SchoolContext context)
{
var students = new List<Student> {
new Student{FirstMidName="Carson",LastName="Alexander",EnrollmentDate=DateTime.Parse("2005-09-01")},
new Student{FirstMidName="Meredith",LastName="Alonso",EnrollmentDate=DateTime.Parse("2002-09-01")},
new Student{FirstMidName="Arturo",LastName="Anand",EnrollmentDate=DateTime.Parse("2003-09-01")},
new Student{FirstMidName="Gytis",LastName="Barzdukas",EnrollmentDate=DateTime.Parse("2002-09-01")},
new Student{FirstMidName="Yan",LastName="Li",EnrollmentDate=DateTime.Parse("2002-09-01")},
new Student{FirstMidName="Peggy",LastName="Justice",EnrollmentDate=DateTime.Parse("2001-09-01")},
new Student{FirstMidName="Laura",LastName="Norman",EnrollmentDate=DateTime.Parse("2003-09-01")},
new Student{FirstMidName="Nino",LastName="Olivetto",EnrollmentDate=DateTime.Parse("2005-09-01")}
};
students.ForEach(s=>context.Students.Add(s));
context.SaveChanges();
var courses = new List<Course> {
new Course{CourseID=1050,Title="Chemistry",Credits=3,},
new Course{CourseID=4022,Title="Microeconomics",Credits=3,},
new Course{CourseID=4041,Title="Macroeconomics",Credits=3,},
new Course{CourseID=1045,Title="Calculus",Credits=4,},
new Course{CourseID=3141,Title="Trigonometry",Credits=4,},
new Course{CourseID=2021,Title="Composition",Credits=3,},
new Course{CourseID=2042,Title="Literature",Credits=4,}
};
courses.ForEach(c=>context.Courses.Add(c));
context.SaveChanges();
var enrollments = new List<Enrollment> {
new Enrollment{StudentID=1,CourseID=1050,Grade=Grade.A},
new Enrollment{StudentID=1,CourseID=4022,Grade=Grade.C},
new Enrollment{StudentID=1,CourseID=4041,Grade=Grade.B},
new Enrollment{StudentID=2,CourseID=1045,Grade=Grade.B},
new Enrollment{StudentID=2,CourseID=3141,Grade=Grade.F},
new Enrollment{StudentID=2,CourseID=2021,Grade=Grade.F},
new Enrollment{StudentID=3,CourseID=1050},
new Enrollment{StudentID=4,CourseID=1050,},
new Enrollment{StudentID=4,CourseID=4022,Grade=Grade.F},
new Enrollment{StudentID=5,CourseID=4041,Grade=Grade.C},
new Enrollment{StudentID=6,CourseID=1045},
new Enrollment{StudentID=7,CourseID=3141,Grade=Grade.A}
};
enrollments.ForEach(e=>context.Enrollments.Add(e));
context.SaveChanges();
}
}
在网站根目录下的webconfig 文件中指定初始化数据。
<entityFramework>
<contexts>
<context type="ContosoUniversity.DAL.SchoolContext">
<databaseInitializer type="ContosoUniversity.DAL.SchoolInitailizer"/>
</context>
</contexts>
如果你不想使用初始化数据,可以在Context节点中指定:disableDatabaseInitialization="true"
注意:此步骤可以省略,因为EF会根据数据库上下文类默认使用连接字符串;
注意数据源的写法:本篇教程使用vs2013开发,作者安装的是EF6.0.0。原文中代码如下:
并指出如果你使用的vs2015,那么要将v11.0替换成MSSQLLocalDB。这种说法是错误的。
而我本地安装的是EF6.1.3 正确写法如下:
</configSections>
<connectionStrings>
<!--<add name="SchoolContext" connectionString="Data Source=.;Initial Catalog=ContosoUniversity1;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>-->
<!--<add name="SchoolContext" connectionString="Data Source=(LocalDb)\mssqllocaldb;Initial Catalog=ContosoUniversity1;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>-->
</connectionStrings>
<appSettings>
如果你想让数据库创建在项目中的App_Data文件夹中,可以在连接字符串中添加AttachDBFilename=|DataDirectory|\ContosoUniversity1.mdf
。
生成项目,添加控制器和视图
添加完成自带视图的控制器,运行项目,即可查看我们刚才添加的数据,这里就不贴图了。
1.关闭浏览器中的Index页面。
2.视图->服务器资源管理器->数据连接
在Student表上右击->显示表数据,结果报错了~~~~。
解决方法:
工具->扩展和更新
重启vs。这样就可以查看表数据了。
注意:如果Web.config中未添加连接字符串,那么在vs中会看不到添加的数据库数据库。如图:
这样,一个简单的应用程序就完成了。
标签:
原文地址:http://www.cnblogs.com/peaceOfMind/p/5315661.html