2010-10-17 67 views
0

我想寫分離linq類的通用代碼。我有什麼目前:設置EntitySet <t>屬性默認使用反射

public void Detach() 
{ 
    this.PropertyChanged = null; 
    this.PropertyChanging = null; 

    this.Categories = default(EntitySet<Categories>); 
    this.Jobs = default(EntitySet<Jobs>); 
    this.Tasks= default(EntitySet<Tasks>); 
} 

這一切正常,但是也有在我的數據庫幾百個表,這將是一個耗時的任務,爲每其中之一做到這一點特別。我所尋找的是通用的東西,我能爲類似於每一個類定義幾乎用途:

public void Detach() 
{ 
    this.PropertyChanged = null; 
    this.PropertyChanging = null; 

    foreach (System.Reflection.PropertyInfo _prop in this.GetType().GetProperties()) 
    { 
     // if _prop is of type EntitySet<T> then set it to default(EntitySet<T>); 
     // TODO: Complete the code here 
    } 
} 

我不確定如何寫代碼預製棒由註釋中描述的任務。可以這樣做,還是我想要做一些在當前框架中無法完成的事情?

編輯:將EntityRef更改爲EntitySet。

回答

1

要做到這一點,最簡單的方法是通過反射來調用你的.dbml產生的初始化方法:

public void Detach() 
{ 
    GetType().GetMethod("Initialize", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(this, null); 
} 

爲了要生成的初始化方法,你必須設置序列化屬性在你的dbml文件改爲「單向」(鼠標右鍵並選擇屬性,你會在屬性檢查器中看到它)。

是的,我感到你的痛苦。