1.用vs2012創建控制台程序
2.設置項目的.net 版本
3.創建Ado.net實體數據模型
3.打開實體數據模型向導Entity Framework有四種模型選擇 來自數據庫的EF設計器(Database First)、空EF設計器(Model First)、空CodeFirst模型(Code First)、來自數據庫的CodeFirst模型(Code First)
4. 選擇已存在的數據庫連接
5.下一步顯示數據庫中所有的表、視圖和存儲過程
備注:
Pluralize or singularize generated object names:如果數據庫中表的名稱是復數,則變為單數形式。如果SchoolDB 數據庫中有Students表,則實體集將是單數的Student,實體的關系如果是一對多、多對多的關系,則關系將是復數形式,例如Student和Course表示多對多的關系,Student實體集中將有復數的屬性名Courses表示Course的集合
Include foreign key columns in the model:包含外鍵屬性明確的表示外鍵。例如,Student與Standard表示一對多的關系,所以一個Student和一個Standard關聯,為了表示這一關系,Student實體中包含StandardId導航屬性,如果不選該項,Student實體僅包含Standard屬性,而不包含StandardId屬性
6.Import selected stored procedures and functions into entity model:自動創建函數引入存儲過程和函數
7.點擊Finish,項目將增加School.edmx文件,雙擊School.edmx文件,將展現表對應的實體以及關系
8.EDM在配置文件中添加鏈接字符串
<connectionStrings> <add name="SchoolDBEntities" connectionString="metadata=res://*/School.csdl|res://*/School.ssdl|res://*/School.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=SchoolDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /> </connectionStrings>
實體-表的映射
EDM中的每一個實體都與數據庫中的表對應
Context上下文和實體類型
在EDM中,每個實體數據模型都會自動生成一個上下文類、與數據庫中表對應的實體類,展開School.edmx,有兩個重要文件{EDM Name}.Context.tt and {EDM Name}.tt:
School.Context.tt:使用T4模板文件生成上下文類,該類繼承DbContext
School.tt T4模板為數據看中的表生成實體類
public partial class Student { public Student() { this.Courses = new HashSet<Course>(); } public int StudentID { get; set; } public string StudentName { get; set; } public Nullable<int> StandardId { get; set; } public byte[] RowVersion { get; set; } public virtual Standard Standard { get; set; } public virtual StudentAddress StudentAddress { get; set; } public virtual ICollection<Course> Courses { get; set; } }
EDM Designer: 描繪概念模型,它包含實體和關系,它看起來很像數據庫表的結構,但是你可以添加、合並和刪除列,你甚至可以添加對象到模型上,可以有與數據庫表不同的列,然而,在模型上的變化都會影響到存儲模型。你可以通過XML文件查看EDM