NHibernate 關系映射中的 Formula
在 Nhibernate 的實體類映射中, 如果實體類的屬性需要通過 SQL 計算才能得到, 則可以使用 Formula 選項解決。
Nhibernate 對 Formula 的要求如下:
formula (optional): an SQL expression that defines the value for a computed property. Computed properties do not have a column mapping of their own.
場景1: 映射需要計算的屬性
以下面的 Category 映射為例:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Northwind" namespace="Northwind">
<class name="Category" table="[Categories]" schema="[dbo]">
<id name="CategoryID" column="[CategoryID]" type="int" />
<property name="CategoryName" column="[CategoryName]" type="string"/>
<property name="Description" column="[Description]" type="string"/>
<property name="Picture" column="[Picture]" type="binary"/>
<set name="Products" lazy="true">
<key column="CategoryID" />
<one-to-many class="Product" not-found="ignore"/>
</set>
</class>
</hibernate-mapping>
如果要增加一個屬性 NameAndDesc , 把 CategoryName 和 Description 兩個字段連接起來, 用 Formula 可以這樣做:
<property name="NameAndDesc" formula="[CategoryName] + ' ' + [Description]" type="string" />
場景2: 映射復雜的 SQL 類型
SQL 2008 支持空間數據類型 geography 和 geometry , 映射空間數據類型可以通過 Nhibernate 的空間擴展解決, 操作起來比較麻煩, 在客戶端不需要空間數據類型或者不能處理空間數據類型的情況下, 可以用 Formula 處理。 示例表結構定義如下:
CREATE TABLE SpatialTable ( id int IDENTITY (1,1), GeogCol1 geography, );
使用 Formula 的映射文件如下:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Northwind" namespace="Northwind">
<class name="Category" table="[Categories]" schema="[dbo]">
<id name="Id" column="[id]" type="int" />
<property name="GeoCol1" formula="[GeogCol1].STAsText()" type="string" />
</class>
</hibernate-mapping>
張志敏所有文章遵循創作共用版權協議,要求署名、非商業 、保持一致。在滿足創作共用版權協議的基礎上可以轉載,但請以超鏈接形式注明出處。
本博客已經遷移到 GitHub , 圍觀地址: https://beginor.github.io/
浙公網安備 33010602011771號