2012-02-15 124 views
4

類似下面的構造是否可行?是否有可能擁有一個Func的參數陣列

public IQueryable<T> AllWithFetch<TRelated>(IQueryable<T> existing, params Expression<Func<T, TRelated>>[] fetchExpressions) 
    { 
    return fetchExpressions.Aggregate(existing, (current, exp) => current.Fetch(exp)); 
    } 

然後可以這樣調用...

var allDetails = this.preGrantDetailRepository 
       .AllWithFetch(this.preGrantDetailRepository.All, x => x.Case, x => x.CaseOwner) 

基本上我想包括增加抓取,NHibernate的戰略,我們的抽象資源庫,使我們能夠從指定這些策略我們的邏輯層沒有破壞存儲庫模式。例如,如果我們從NHibernate更改爲另一個ORM,那麼我們可以提供相同的存儲庫方法,但實現該ORM。

當我嘗試鏈接param數組中的多個func時,會出現問題。

所以此工程...

var allDetails = this.preGrantDetailRepository 
       .AllWithFetch(this.preGrantDetailRepository.All, x => x.Case) 

但這種失敗的messge

var allDetails = this.preGrantDetailRepository 
       .AllWithFetch(this.preGrantDetailRepository.All, x => x.Case, x => x.CaseOwner) 

我使用.NET 3.5,存儲庫模式 「的類型參數不能從他們的使用推斷」 ,功能NHibernate,SQL Server 2008中

編輯

我在下面Porges的幫助下解決了這個問題,所以我已經準備好了。問題確實來自TRelated的錯誤使用。下面是資源庫中的工作方法......

public IQueryable<T> AllWithFetch<T>(IQueryable<T> existing, params Expression<Func<T, Entity>>[] fetchExpressions) 
     { 
      return fetchExpressions.Aggregate(existing, (current, exp) => current.Fetch(exp)); 
     } 

它現在AllWithFetch不TRelated,我使用的函數功能超類的兩個實體(案例& CaseOwner)。

感謝您的幫助球員

+0

'.Case'和'.CaseOwner'的返回類型是什麼? – AakashM 2012-02-15 10:33:03

回答

4

的問題是你TRelated,這不是什麼關係params明確。

試試這個,例如:

void DoSomething<T,U>(Func<T,U> f, Func<T,U> f2) 
{ 
} 

void Main() 
{ 
    DoSomething((int x) => x + 1, (int x) => x + ""); 
} 

編譯器會推斷T必須int,但不能推斷出良好類型U(我不知道的確切細節,但它通常不會在繼承鏈上尋找更高的類型)。

爲了使它起作用,您需要指定超類;在這種情況下,object

void Main() 
{ 
    DoSomething<int,object>((int x) => x + 1, (int x) => x + ""); 
} 

所以你要麼需要指定自己一個超類(這看起來將是object這裏),或只是擺脫TRelated參數。

2

你應該TRelated爲每個FUNC返回值。 .Case和.CaseOwner的類型是否相同?如果沒有,你可以使用

Func<T, object> 

代替(或任何界面)

相關問題