2011-03-21 110 views
0

我有一個關於返回我認爲是來自服務操作的IQueryable的轉換問題,但顯然是一個DbQuery。WCF數據服務操作投問

更新:我立足我的一些代碼(ServiceOp,返回的IEnumerable)關閉斯科特Hanselman的post here的:

[WebGet] 
     public IQueryable<Post> GetPopularPosts() 

我已經建立了基本的WCF DataService的。根據update bug,我將其定義爲:

public class Api : DataService<ObjectContext> 

而不是來自TestDb。我安裝了的createDataSource()爲:

protected override ObjectContext CreateDataSource() 
{ 
    var testDb = new TestDb(); 
    var objectContext = ((IObjectContextAdapter)testDb).ObjectContext; 
    objectContext.ContextOptions.ProxyCreationEnabled = false; 
    return objectContext; 
} 

在我InitializeService方法,我稱之爲:

config.SetServiceOperationAccessRule("GetStuff", ServiceOperationRights.AllRead); 

我的服務操作:

[WebGet] 
public IQueryable<Stuff> GetStuff() 
{ 
    var context = new TestDb(); 
    return context.Stuff; 
} 

的問題是,即使方法完成,context.Stuff中有項目,服務器返回錯誤:

An error occurred while processing this request. Exception has been thrown by the target of an invocation. System.Reflection.TargetInvocationException 
... 
Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery' to type 'System.Linq.IQueryable` 

對此有何想法?

+0

你可以在這裏添加上下文代碼。 Stuff和Context中的其他對象之間是否有任何關係? – 2011-03-21 07:16:32

回答

2

請記住,WCF服務無法返回接口類型!他們需要具體的DataContract-ed類型。特別是IQueryable,因爲IQueryable對象實際上是「如何調用數據」而不是實際的數據。

嘗試返回一個列表,而不是:

[WebGet] 
public List<Stuff> GetStuff() 
{ 
    var context = new TestDb(); 
    return context.Stuff.ToList(); 
} 

編輯

顯然,你可以返回IEnumerable的,但不是IQueryable的。考慮到我對IQueryable的解釋,這是有道理的。

+0

謝謝文森特,就是這樣。我從Scott Hanselman的帖子中獲得Service Service(在上面的更新中提到)。事實上,網絡上充斥着返回IQueryable的例子。呃... – teleball 2011-03-22 02:51:39

+0

文森特,我想標記你的答案是正確的,但我認爲你需要詳細闡述一件事。在對你的答案進行研究之後,我發現這可能有點誤導。你*可以*設置返回類型爲接口類型,但不是IQueryable。例如,IEnumerable很好。簡單地將IQueryable換成IEnumerable,一切正常。您不需要List或顯式轉換.ToList()。再次感謝您讓我走向正確的道路。 – teleball 2011-03-22 03:07:19