跳转到内容

Entity Framework

维基百科,自由的百科全书

这是本页的一个历史版本,由Regionbbs留言 | 贡献2008年9月15日 (一) 13:23编辑。这可能和当前版本存在着巨大的差异。

File:ANEF.PNG
ADO.NET Entity Framework stack

ADO.NET Entity Framework 是微軟以 ADO.NET 為基礎所發展出來的物件關聯對應 (O/R Mapping) 解決方案,早期被稱為 ObjectSpace,現已經包含在 Visual Studio 2008 Service Pack 1 以及 .NET Framework 3.5 Service Pack 1 中發表。

ADO.NET Entity Framework 以 Entity Data Model (EDM) 為主,將資料邏輯層切分為三塊,分別為 Conceptual Schema, Mapping Schema 與 Storage Schema 三層,其上還有 Entity Client,Object Context 以及 LINQ 可以使用。

架構

概念層結構

概念層結構定義了物件模型 (Object Model),讓上層的應用程式碼可以如物件導向的方式般存取資料,概念層結構是由 CSDL (Conceptual Schema Definition Language) 所撰寫。

一份概念層結構定義如下所示:

<?xml version="1.0" encoding="utf-8"?>
<Schema Namespace="Employees" Alias="Self" xmlns="http://schemas.microsoft.com/ado/2006/04/edm">
  <EntityContainer Name="EmployeesContext">
    <EntitySet Name="Employees" EntityType="Employees.Employees" />
  </EntityContainer>
  <EntityType Name="Employees">
    <Key>
      <PropertyRef Name="EmployeeId" />
    </Key>
    <Property Name="EmployeeId" Type="Guid" Nullable="false" />
    <Property Name="LastName" Type="String" Nullable="false" />
    <Property Name="FirstName" Type="String" Nullable="false" />
    <Property Name="Email" Type="String" Nullable="false" />
  </EntityType>
</Schema>

對應層結構

對應層結構負責將上層的概念層結構以及下層的儲存體結構中的成員結合在一起,以確認資料的來源與流向。對應層結構是由 MSL (Mapping Specification Language) 所撰寫。

一份對應層結構定義如下所示:

<?xml version="1.0" encoding="utf-8"?>
<Mapping Space="C-S" xmlns="urn:schemas-microsoft-com:windows:storage:mapping:CS">

  <EntityContainerMapping StorageEntityContainer="dbo" CdmEntityContainer="EmployeesContext">
    <EntitySetMapping Name="Employees" StoreEntitySet="Employees" TypeName="Employees.Employees">

      <ScalarProperty Name="EmployeeId" ColumnName="EmployeeId" />
      <ScalarProperty Name="LastName" ColumnName="LastName" />
      <ScalarProperty Name="FirstName" ColumnName="FirstName" />
      <ScalarProperty Name="Email" ColumnName="Email" />

    </EntitySetMapping>
  </EntityContainerMapping>
</Mapping>

儲存層結構

儲存層結構是負責與資料庫管理系統 ((DBMS)) 中的資料表做實體對應 (Physical Mapping),讓資料可以輸入正確的資料來源中,或者由正確的資料來源取出。它是由 SSDL (Storage Schema Definition Language) 所撰寫。

一份儲存層結構定義如下所示:

?xml version="1.0" encoding="utf-8"?>
<Schema Namespace="Employees.Store" Alias="Self"
    Provider="System.Data.SqlClient"
    ProviderManifestToken="2005"
    xmlns="http://schemas.microsoft.com/ado/2006/04/edm/ssdl">
  <EntityContainer Name="dbo">
    <EntitySet Name="Employees" EntityType="Employees.Store.Employees" />
  </EntityContainer>
  <EntityType Name="Employees">
    <Key>
      <PropertyRef Name="EmployeeId" />
    </Key>
    <Property Name="EmployeeId" Type="uniqueidentifier" Nullable="false" />
    <Property Name="LastName" Type="nvarchar" Nullable="false" MaxLength="50" />
    <Property Name="FirstName" Type="nvarchar" Nullable="false" />
    <Property Name="Email" Type="nvarchar" Nullable="false" />
  </EntityType>
</Schema>

用戶端支援

當定義好 Entity Data Model 的 CS/MS/SS 之後,即可以利用 ADO.NET Entity Framework 的用戶端來存取 EDM,EDM 中的資料提供者會向資料來源存取資料,再傳回用戶端。

目前 ADO.NET Entity Framework 有三種用戶端:

Entity Client

Entity Client 是 ADO.NET Entity Framework 中的原生用戶端 (Native Client),它的物件模型和 ADO.NET 的其他用戶端非常相似,一樣有 Connection, Command, DataReader 等物件,但最大的差異就是,它有自己的 SQL 指令 (Entity SQL),可以用 SQL 的方式存取 EDM,簡單的說,就是把 EDM 當成一個實體資料庫。

// Initialize the EntityConnectionStringBuilder.
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();

//Set the provider name.
entityBuilder.Provider = providerName;

// Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = providerString;

// Set the Metadata location.
entityBuilder.Metadata =  @"res://*/AdventureWorksModel.csdl|
                            res://*/AdventureWorksModel.ssdl|
                            res://*/AdventureWorksModel.msl";

Console.WriteLine(entityBuilder.ToString());

using (EntityConnection conn = new EntityConnection(entityBuilder.ToString()))
{
    conn.Open();
    Console.WriteLine("Just testing the connection.");
    conn.Close();
}

Object Context

由於 Entity Client 太過於制式,而且也不太符合 ORM 的精神,因此微軟在 Entity Client 的上層加上了一個供程式語言直接存取的介面,它可以把 EDM 當成物件般的存取,此介面即為 Object Context (Object Service)。

在 Object Context 中對 EDM 的任何動作,都會被自動轉換成 Entity SQL 送到 EDM 中執行。

// Get the contacts with the specified name.
ObjectQuery<Contact> contactQuery = context.Contact
    .Where("it.LastName = @ln AND it.FirstName = @fn",
    new ObjectParameter("ln", lastName), 
    new ObjectParameter("fn", firstName));

LINQ to Entities

Object Context 將 EDM 的存取改變為一種對物件集合的存取方式,這也就讓 LINQ 有了發揮的空間,因此 LINQ to Entities 也就由此而生,簡單的說,就是利用 LINQ 來存取 EDM,讓 LINQ 的功能可以在資料庫中發揮。

using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectQuery<Product> products = AWEntities.Product;

    IQueryable<Product> productNames =
       from p in products
       select p;
}

開發工具

目前 ADO.NET Entity Framework 的開發,在 Visual Studio 2008 中有充份的支援,在安裝 Visual Studio 2008 Service Pack 1 後,檔案範本中即會出現 ADO.NET 實體資料模型 (ADO.NET Entity Data Model) 可讓開發人員利用 Entity Model Designer 來設計 EDM,EDM 亦可由記事本或文字編輯器所編輯。

衍生服務

微軟特別針對了網路上各種不同的應用程式 (例如 AJAX, Silverlight, Mashup 應用程式) 開發了一個基於 ADO.NET Entity Framework 之上的服務,稱為 ADO.NET Data Services (專案代號為 Astoria),並與 ADO.NET Entity Framework 一起包裝在 .NET Framework 3.5 Service Pack 1 中發表。

參考資料

本文的參考程式碼皆來自於 MSDN Library : ADO.NET Entity Framework 中。