2011-03-10 25 views
0

我不能完全弄清楚這一點。爲了簡單起見,我會解釋我想要做的事情。C#使用反射和linq替換另一個通用對象屬性

目前,我正在使用一個使用存儲庫模式的nHibernate項目。數據庫內部有一堆有「描述」字段的表。現在,我試圖將這些表本地化以使用通用的「資源」表。

所以,我有這2個表:

表1 - 資源: RESOURCEID,LanguageId,價值

表2 - LinkLabels: LinkLabelId,說明,RESOURCEID

然後有一個會話令牌包含一個「LanguageId」,它是用戶的首選語言。

好了,就這樣說,我需要做的是從ResourceTable中獲取「Value」,其中來自Resources的LinkLabels = ResourceId的ResourceId代表具有「ResourceId」的對象。但我必須使用Generic類型來完成此操作。

這是我到目前爲止有:

public IQueryable<T> ToQueryable<T>() 
{ 
    try 
    { 
     PropertyInfo resourceProperty = typeof(T).GetProperty("ResourceKey"); 

     if (resourceProperty != null) 
     { 
      // Somthing like this, but of course this won't work 
      // because x.ResourceId doesn't exist because of generic, and the select 
      // statement is invalue. 
      // 
      // return from x in this.session.Query<T>() 
      //  join p in this.session.Query<Resource>() on x.ResourceId equals p.ResourceId 
      //  where p.LanguageId = 1 // this will be from a session object, hardcoded to 1 for now 
      //  select x where x.Description is p.value; 
     } 
     else 
     { 
      return this.session.Query<T>(); 
     } 
    } 
    catch (Exception ex) 
    { 
     throw ex; 
    } 
} 

回答

1

創建這樣一個接口:

接口的IResource { INT RESOURCEID {獲得;設置;}}

然後用約束:

公共IQueryable的ToQueryable()其中T:的IResource { ... }

然後你必須讓所有的類型都實現的IResource爲好。

+0

是的,我也想到了這一點,希望它真的與對象斷開連接,但它看起來並不像在建立關係時這種可能性。 – Dave 2011-03-11 15:45:42

相關問題