EF 早期版本設計器不支援複雜類型,需手動修改 EDMX(CSDL/MSL)方能使用。本文以 Northwind Customers 表為例,將 Address、City、Region、Country、PostalCode 合併為複雜類型 CommonAddress。
<EntityType Name="Customers"> 移除原五個純量屬性,新增 <Property Name="Address" Type="NorthwindModel.CommonAddress" Nullable="false" />;並補上 <ComplexType Name="CommonAddress"> 定義五個子屬性。ComplexProperty 內對應各子屬性。<EntityType Name="Customers">
<Key><PropertyRef Name="CustomerID" /></Key>
<Property Name="CustomerID" Type="String" ... />
...
<Property Name="Address" Type="NorthwindModel.CommonAddress" Nullable="false" />
...
</EntityType>
<ComplexType Name="CommonAddress">
<Property Name="Address" Type="String" MaxLength="60" ... />
<Property Name="City" Type="String" MaxLength="15" ... />
<Property Name="Region" Type="String" MaxLength="15" ... />
<Property Name="PostalCode" Type="String" MaxLength="10" ... />
<Property Name="Country" Type="String" MaxLength="15" ... />
</ComplexType>
完成後即可在程式碼以 customer.Address.City 等屬性存取,提升領域模型表達力。