Entity Data Model (EDM) 是 .NET Framework 3.5 SP1 引入的進階 ORM,超越 LINQ to SQL,讓開發者專注領域模型而非資料庫互動細節。本系列深入解析 EDMX 結構、視覺化工具、映射關係、產生程式碼與文檔特性。
以 XML 開啟 .edmx 可見三部分:
通常無需手動編輯 EDMX,透過視覺化設計師、Mapping Details、Model Browser 操作。編譯時 MSBuild 將三區段分別輸出為 .csdl、.ssdl、.msl 至輸出目錄。
左側顯示概念模型 (實體、關聯、繼承),右側顯示儲存模型 (資料表、檢視、存儲程序),提供完整模型概覽與導航。



// LINQ to SQL
[Table(Name="dbo.Employees")]
public partial class Employee : INotifyPropertyChanging, INotifyPropertyChanged
// EDM EntityObject
[EdmEntityTypeAttribute(NamespaceName="NorthwindModel", Name="Employee")]
[DataContractAttribute()]
[Serializable()]
public partial class Employee : EntityObject
EDM 實體繼承 EntityObject (提供變更追蹤、關聯管理),而非介面實作。標記 DataContract 支援 WCF 序列化。
// LINQ to SQL: 建構函式初始化 EntitySet/EntityRef
public Employee() { ... EntitySet 初始化 ... OnCreated(); }
// EDM: 靜態 Create 方法,強制要求非 nullable 屬性
public static Employee CreateEmployee(int employeeID, string lastName, string firstName)
{
Employee e = new Employee();
e.EmployeeID = employeeID; e.LastName = lastName; e.FirstName = firstName;
return e;
}
EDM 透過 Factory Method 確保實體建立時即處於有效狀態。
// LINQ to SQL
[Column(Storage="_EmployeeID", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public int EmployeeID { get { ... } set { ... SendPropertyChanging/Changed ... } }
// EDM
[EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[DataMemberAttribute()]
public int EmployeeID {
get { return _EmployeeID; }
set {
OnEmployeeIDChanging(value);
ReportPropertyChanging("EmployeeID");
_EmployeeID = StructuralObject.SetValidValue(value);
ReportPropertyChanged("EmployeeID");
OnEmployeeIDChanged();
}
}
Getter/Setter 邏輯相似,EDM 使用 ReportPropertyChanging/Changed 而非 SendPropertyChanging/Changed,並透過 StructuralObject.SetValidValue 驗證非空值。
// LINQ to SQL
public Table<Employee> Employees { get { return GetTable<Employee>(); } }
// EDM
[Browsable(false)]
public ObjectQuery<Employee> Employees
{
get {
if (_Employees == null) _Employees = base.CreateQuery<Employee>("[Employees]");
return _Employees;
}
}
EDM 透過 ObjectContext.CreateQuery 執行 Entity SQL,支援延遲載入。
// LINQ to SQL
[DatabaseAttribute(Name="Northwind")]
public partial class NorthwindDataContext : DataContext
// EDM
public partial class NorthwindEntities : ObjectContext
ObjectContext 負責連線管理、查詢執行、持久化、變更追蹤。連線字串包含中繼資料路徑與資料庫連線字串:
metadata=.\NorthwindModel.csdl|.\NorthwindModel.ssdl|.\NorthwindModel.msl;
provider=System.Data.SqlClient;provider connection string="Data Source=...;MultipleActiveResultSets=True"
EDM 實體類型、關聯、屬性皆有 Documentation 屬性,會同步更新產生之 partial 類別的 XML 註解,支援文檔產生工具 (如 Sandcastle)。

/// <summary>
/// Employee entity which corresponds with the Northwind.Employees table
/// </summary>
/// <KeyProperties>
/// EmployeeID
/// </KeyProperties>