全面掌握 NBearV3 ORM 進階功能:實體自關聯設計、效能相關屬性(IndexProperty、BatchUpdate)配置、Gateway 強型別查詢方法在不同屬性設定下的效能差異分析。
基於 ORM_Tutorial 複製專案重命名為 ORM_Adv_Tutorial,引用 dist 目錄 DLL 與基礎教學程式碼。
[IndexProperty]
Guid ParentID { get; set; }
標記後,生成資料庫腳本時自動為該欄位建立單欄索引,提升以此欄位為條件的查詢效能。
[FkQuery("ParentID", Contained=true, LazyLoad=true)]
Group[] SubGroups { get; set; }
Group 實體 1 對多關聯自身,形成樹狀結構。注意: NBearV3 不支援多對多自關聯,也不支援繼承體系中的多對多關聯。
[BatchUpdate(10)]
public interface User : Entity { ... }
[BatchUpdate(10)]
public interface LocalUser : User { ... }
效能影響驚人:原本 20 個級聯 Delete 需 20 次連線,設 BatchUpdate(10) 後僅需 2 次連線(每 10 筆一批)。
EntityDesignToEntity.exe 載入 DLLEntities\Entities.cswebsite\EntityConfig.xmlwebsite\db.sql(於 SQL Server tempdb 執行)刪除 Default.aspx.cs 原始碼,參考教學目錄範例建立新頁面,展示 Gateway 大多數強型別查詢方法。
LazyLoad=true 首次存取時載入,LazyLoad=false 實例化即載入,SQL 日誌明顯可見new Entity() → IsAttached() == false → Save() 執行 InsertGateway.Find() 取得 → IsAttached() == true → Save() 僅 Update 修改欄位new User { ID=id }.Attach(); user.Status=...; gateway.Save(user); 僅 1 次 UpdateOnPropertyChanged 事件:user.Detach(); /* 批量修改 */ user.Attach(); gateway.Save(user);gateway.RegisterSqlLogger(new LogHandler(WriteLine)); // 註冊 SQL 日誌輸出
// 開發/調試/效能優化必備,監控強型別 API 底層真實 SQL 互動
善用 IndexProperty 建立索引、BatchUpdate 減少資料庫往返、LazyLoad 控制載入時機、Attach/Detach 靈活切換持久化狀態,配合 SqlLogger 監控 SQL,能構建高效能 ORM 應用。