2011-03-21 83 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