(完全限定類名:DataRabbit.ORM.IEntityRelationLoader)
在DataRabbit架構提供的ORM功能之中,除了IOrmAccesser介面展現的核心ORM功能外,IEntityRelationLoader介面也提供了一些有意義的功能。正如其名,IEntityRelationLoader是通過資料表的主外鍵關係來載入當前Entity的Parent和Children。
現在對我們前面樣本經常用到的Student資料表做個擴充,假設,Student表的MentorID欄位作為外鍵,指向Mentor表;而且,Book表中的StudentID欄位也是外鍵,指向Student表。這種主外鍵關係的含義是:“一個學生有一個導師,並且擁有多本書”。這三個表的關係圖如下所示:
通過對Student擴充後,我們可以為Student Entity Class 加上如下兩個屬性,來反映這種關係:
#region Mentor
[NonSerialized]
private Mentor m_Mentor = null ;
public Mentor Mentor
{
get
{
return this.m_Mentor ;
}
set
{
this.m_Mentor = value ;
}
}
#endregion
#region BookList
[NonSerialized]
private IList<Book> m_BookList = null ;
public IList<Book> BookList
{
get
{
return this.m_BookList ;
}
set
{
this.m_BookList = value ;
}
}
#endregion
我將這種通過主外鍵關係得到的屬性稱為“FamilyRelation”屬性,如果使用EntityCreator工具產生Entity Class,這些屬性都會根據資料表關係而自動產生。
現在,我們來調用如下語句: Student student = stuOrmAccesser.GetOne(new Filter(Student._ID, 30));
結果會發現,返回的student對象的Mentor屬性和BookList屬性不會被填充。如果不使用IEntityRelationLoader介面,而是直接通過IOrmAccesser來擷取這個student的“Family”,我們需要這樣做: Student student = stuOrmAccesser.GetOne(new Filter(Student._ID, 30));
student.Mentor = stuOrmAccesser.GetParent<Mentor>(student);
student.BookList = stuOrmAccesser.GetChildList<Book>(student);
像這樣子可以達到目的,但是未免繁瑣了一點,如果Student表有多個外鍵,則我們就要調用多次GetParent()方法來分別擷取各個Parent;對於多個Children,也是如此。IEntityRelationLoader介面使得這種基於關係的載入變得非常簡單,如上述功能使用下面的代碼即可實現: entityRelationLoader.LoadFamily(student);
LoadFamily方法一次調用可以載入當前student對象的所有“Family”成員(注意,這裡的載入“Family”只包括載入自己Parent和Children,而不包括更上的grandfather或更下的grandson等)。
我們可以從DataRabbit的進入點IDataAccesser介面擷取IEntityRelationLoader引用: IEntityRelationLoader entityRelationLoader = dataAccesser.GetEntityRelationLoader(null);
通過上面的樣本,我們對IEntityRelationLoader的功能已經有了一些瞭解。下面我們來看看這個介面的全貌: public interface IEntityRelationLoader :ITransactionAccesser
{
/// <summary>
/// LoadChildren 載入自己的children到對應的屬性欄位(如果Entity提供了這些屬性欄位,並且屬性可寫)上。
/// </summary>
void LoadChildren(object entity);
/// <summary>
/// LoadParents 載入自己的parents到對應的屬性欄位(如果Entity提供了這些屬性欄位,並且屬性可寫)上。
/// </summary>
void LoadParents(object entity);
/// <summary>
/// LoadFamily 載入自己的parents和children到對應的屬性欄位(如果Entity提供了這些屬性欄位,並且屬性可寫)上。
/// </summary>
void LoadFamily(object entity);
/// <summary>
/// LoadOffspring 以當前entity為根,載入所有後代。注意,自己以及後代的所有Parent屬性都不會被賦值。
/// </summary>
void LoadOffspring(object entity);
}
轉到:DataRabbit 輕量的資料訪問架構 -- 序