MVC3+EF4.1學習系列(一)-------創(chuàng)建EF4.1 code first的第一個實例
基于EF4.1 code first 簡單的CRUD 園子中已經(jīng)有很多了 ~~ 真不想再寫這個了 可是為了做一個完整的小demo 從開始 到后面的一些簡單重構 還是決定認真把這個寫出來
爭取寫些別人沒寫到的東西~~ 好了 開始~~
這次要做的是個學校管理的demo(通俗些)
先建一個MVC3的應用程序 因為我們是code first 所以 開始創(chuàng)建實體類
一.創(chuàng)建Model

學生和學生成績登記表是一對多的關系 一個學生可以有多次登記 (因為有多個課程) 一個課程也可以有多個登記 可以看出 其實就是 學生和課程 存在一個多對多的關系
為什么這么建立模型呢?這節(jié)主要不是討論關系 關系這個會放到 第三節(jié)來討論~~
現(xiàn)在開始創(chuàng)建學生的實體類
using System;
using System.Collections.Generic;
namespace ContosoUniversity.Models
{
public class Student
{
public int StudentID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
}
在這里面 這個StudentID將被默認的設為主鍵 EF將會默認的給名字為ID的或者帶ID的設置為主鍵
而Enrollments是一個導航屬性 將做為外鍵 導航屬性定義為virtual 以便于實現(xiàn)延遲加載
接下來 創(chuàng)建登記錄入表(關系表)的實體類
using System;
using System.Collections.Generic;
namespace ContosoUniversity.Models
{
public class Enrollment
{
public int EnrollmentID { get; set; }
public int CourseID { get; set; }
public int StudentID { get; set; }
public decimal? Grade { get; set; }
public virtual Course Course { get; set; }
public virtual Student Student { get; set; }
}
}
這里面 我們的成績是可空類型 學生實體有多個 Enrollment 而Enrollment有一個學生實體的導航屬性 這里面 我們既有學生ID 又有學生實體屬性 我們會擔心 會不會生成兩個呢StudentID?不用擔心 EF很聰明 在關系表里 只有一個studentID
接下來就是創(chuàng)建課程實體了
using System;
using System.Collections.Generic;
namespace ContosoUniversity.Models
{
public class Course
{
public int CourseID { get; set; }
public string Title { get; set; }
public int Credits { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
}
OK了 實體創(chuàng)建好了 接下來 我們要創(chuàng)建一個 數(shù)據(jù)庫上下文
二.Creating the Database Context
這個類主要是把上面創(chuàng)建的實體類包含再里面 指定哪些實體類包含在我們的數(shù)據(jù)模型中 還有 這個類可以指定我們的映射關系 還可以指定一些生成的約束關系總之 很有用的
這里面 我們先創(chuàng)建一個DAL的文件夾 然后在下面新建一個類 叫做SchoolContext 并且繼承DbContext
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.Entity;
using ContosoUniversity.Models;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Data.Entity.Infrastructure;
namespace ContosoUniversity.DAL
{
public class SchoolContext:DbContext
{
private readonly static string CONNECTION_STRING = "name=WlfSys_EFCF_ConnString";
public DbSet<Student> Students { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
public DbSet<Course> Courses { get; set; }
public SchoolContext()
: base(CONNECTION_STRING)//不寫這個 默認的就是SchoolContext
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();//移除復數(shù)表名的契約
modelBuilder.Conventions.Remove<IncludeMetadataConvention>();//防止黑幕交易 要不然每次都要訪問 EdmMetadata這個表
/*
可以刪除的公約有:
Namespace:System.Data.Entity.ModelConfiguration.Conventions.Edm
? AssociationInverseDiscoveryConvention
尋找導航上互相引用的類的屬性,并將它們配置為逆屬性的相同的關系。
? ComplexTypeDiscoveryConvention
尋找有沒有主鍵的類型,并將它們配置為復雜類型。
? DeclaredPropertyOrderingConvention
確保每個實體的主要關鍵屬性優(yōu)先于其他屬性。
? ForeignKeyAssociationMultiplicityConvention
配置是必需的還是可選的關系基于為空性外鍵屬性,如果包含在類定義中。
? IdKeyDiscoveryConvention
查找名為 Id 或 <TypeName> Id 的屬性,并將他們配置作為主鍵。
? NavigationPropertyNameForeignKeyDiscoveryConvention
使用外鍵關系,使用 <NavigationProperty> <PrimaryKeyProperty> 模式作為屬性的外觀。
? OneToManyCascadeDeleteConvention
交換機上層疊刪除,所需的關系。
? OneToOneConstraintIntroductionConvention
將配置為一個: 一個關系的外鍵的主鍵。
? PluralizingEntitySetNameConvention
配置為多元化的類型名稱的實體數(shù)據(jù)模型中的實體集的名稱。
? PrimaryKeyNameForeignKeyDiscoveryConvention
使用外鍵關系,使用 <PrimaryKeyProperty> 模式作為屬性的外觀。
? PropertyMaxLengthConvention
配置所有的字符串和字節(jié) [] 屬性,默認情況下具有最大長度。
? StoreGeneratedIdentityKeyConvention
配置默認情況下將標識所有整數(shù)的主鍵。
? TypeNameForeignKeyDiscoveryConvention
使用外鍵關系,使用 <PrincipalTypeName> <PrimaryKeyProperty> 模式作為屬性的外觀。
*/
}
}
}
詳細的解釋下這里
private readonly static string CONNECTION_STRING = "name=WlfSys_EFCF_ConnString";
public SchoolContext()
: base(CONNECTION_STRING)//不寫這個 默認的就是SchoolContext
{
}
上面這里是配置連接字符串 默認的就是SchoolContext 即你這個context的名字
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();//移除復數(shù)表名的契約
modelBuilder.Conventions.Remove<IncludeMetadataConvention>();//防止黑幕交易 要不然每次都要訪問 EdmMetadata這個表
}
再重寫的這個方法里 我們可以移除一些契約 還可以配置數(shù)據(jù)庫映射關系 常用的移除信息 都寫在里面了
三.設置連接字符串
<connectionStrings>
<add name="WlfSys_EFCF_ConnString"
providerName="System.Data.SqlClient" connectionString="Data Source=.;Initial Catalog=WLFSchool;Integrated Security=True;Pooling=False" />
</connectionStrings>
我們的這個名字 和上面設置的一直~~(那個英文博客里用的是 SQL Server Compact database 但為了讓項目貼近實際 我這里用SQL2005)
四.數(shù)據(jù)庫數(shù)據(jù)初始化
在DAL下 新建一個類 SchoolInitializer 繼承自 DropCreateDatabaseIfModelChanges<SchoolContext> 這個類主要實現(xiàn) 數(shù)據(jù)庫數(shù)據(jù)初始化 方便測試~~
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;//記得引用命名空間
using ContosoUniversity.Models;
namespace ContosoUniversity.DAL
{
public class SchoolInitializer : DropCreateDatabaseIfModelChanges<SchoolContext>
{
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 { Title = "Chemistry", Credits = 3, },
new Course { Title = "Microeconomics", Credits = 3, },
new Course { Title = "Macroeconomics", Credits = 3, },
new Course { Title = "Calculus", Credits = 4, },
new Course { Title = "Trigonometry", Credits = 4, },
new Course { Title = "Composition", Credits = 3, },
new Course { Title = "Literature", Credits = 4, }
};
courses.ForEach(s => context.Courses.Add(s));
context.SaveChanges();
var enrollments = new List<Enrollment>
{
new Enrollment { StudentID = 1, CourseID = 1, Grade = 1 },
new Enrollment { StudentID = 1, CourseID = 2, Grade = 3 },
new Enrollment { StudentID = 1, CourseID = 3, Grade = 1 },
new Enrollment { StudentID = 2, CourseID = 4, Grade = 2 },
new Enrollment { StudentID = 2, CourseID = 5, Grade = 4 },
new Enrollment { StudentID = 2, CourseID = 6, Grade = 4 },
new Enrollment { StudentID = 3, CourseID = 1 },
new Enrollment { StudentID = 4, CourseID = 1, },
new Enrollment { StudentID = 4, CourseID = 2, Grade = 4 },
new Enrollment { StudentID = 5, CourseID = 3, Grade = 3 },
new Enrollment { StudentID = 6, CourseID = 4 },
new Enrollment { StudentID = 7, CourseID = 5, Grade = 2 },
};
enrollments.ForEach(s => context.Enrollments.Add(s));
context.SaveChanges();
}
}
}
這樣還沒有完 還要再 Global.asax 下的Application_Start()加上如下代碼
Database.SetInitializer<SchoolContext>(new SchoolInitializer());
五.創(chuàng)建控制器

創(chuàng)建好后添加
private SchoolContext db = new SchoolContext();
再在Index方法下添加得到所有學生的方法
public ViewResult Index()
{
return View(db.Students.ToList());
}
六.添加視圖(小談MVC的 DISPLAY)
@model IEnumerable<ContosoUniversity.Models.Student>
@{
ViewBag.Title = "Students";
}
<h2>Students</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th></th>
<th>Last Name</th>
<th>First Name</th>
<th>Enrollment Date</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.StudentID }) |
@Html.ActionLink("Details", "Details", new { id=item.StudentID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.StudentID })
</td>
<td>
@Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.FirstMidName)
</td>
<td>
@Html.DisplayFor(modelItem => item.EnrollmentDate)
</td>
</tr>
}
</table>
好了 視圖添加完了 這里面 我們用了 Html.DisplayFor 剛看到這個時 總是不明白這個到底顯示什么 還有實體類上 總是加上display(name="")這樣的特性 但是又和這個沒關系 讓我很郁悶
查了MSDN和相關資料 終于明白 Html.DisplayFor 可以算是顯示模版 顯示實體類的特性[DataType(DataType.Password)] 這樣顯示的就是密碼框 而 display(name="")這樣的特性 則是讓 Html.LabelFor()去顯示的 display的具體的 可以看下這個文章 介紹的不錯 display模版詳細介紹
七.運行環(huán)境 查看結果

大家一定很關心數(shù)據(jù)庫的生成什么樣子滴~~

EdmMetadata 數(shù)據(jù)庫記錄個版本對照 可以不要 在契約里有刪除~~用站長dudu的話 防止黑幕交易
八.總結
很簡單的創(chuàng)建一個EF4.1 代碼優(yōu)先的小例子 沒什么難度~~ 但還是認真的寫了下來 好累哦
下一節(jié) 講基本的增刪改查操作 以及中間發(fā)生的狀態(tài)的變更

浙公網(wǎng)安備 33010602011771號