我有下面的代碼位:如何從實體框架導航屬性創建LINQ表達式?
Expression<Func<Subscription, Service>> service2= subscription => (from relationship in subscription.ChildRelationships
select relationship.SecondService).FirstOrDefault();
它創建以後可以使用作爲與所述實體框架查詢的一部分的表達式。我使用的實際代碼有一個where子句,但爲了便於閱讀,我省略了它。這工作正常,我可以在我用於測試的LINQPad中運行它。
如果我改變代碼:
Expression<Func<Subscription, IQueryable<Service>>> service2= subscription => (from relationship in subscription.ChildRelationships
select relationship.SecondService);
它不再編譯,並具有以下錯誤:
Cannot convert lambda expression to delegate type 'System.Func<Farmworks.Data.Subscription,System.Linq.IQueryable<Farmworks.Data.Service>>' because some of the return types in the block are not implicitly convertible to the delegate return type
這似乎是因爲ChildRelationships這是一個導航屬性未實現IQueryable的。它實際上是EntityCollection類型的,它實現了IEnumerable,但對於創建與EF一起工作的表達式來說並不合適。
我想我明白爲什麼第二塊代碼不起作用,並想知道如何重寫它,以便它可以。還有一個令我感到困惑的是爲什麼第一塊代碼確實有效。它還使用ChildRelationships導航屬性,但沒有任何問題成爲可與EF一起使用的表達式。
任何人都可以擺脫任何光線?
嘗試了代碼,但得到了以下結果: 在源類型爲「System.Data.Objects.DataClasses.EntityCollection 」。在對「SelectMany」的調用中,類型推斷失敗。 – GiddyUpHorsey 2009-05-28 21:54:50