【问题标题】:WCF Data Service Operation cast issueWCF 数据服务操作转换问题
【发布时间】:2011-03-22 16:58:52
【问题描述】:

我在从服务操作返回我认为是 IQueryable 的内容时遇到了强制转换问题,但显然是 DbQuery。

更新:我的一些代码(ServiceOp,返回 IEnumerable)基于 Scott Hanselman 的 post here

[WebGet]
        public IQueryable<Post> GetPopularPosts()

我已经设置了一个基本的 WCF 数据服务。根据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`

对此有什么想法吗?

【问题讨论】:

  • 你能在这里添加上下文代码吗? Stuff 和 Context 中的其他对象有什么关系吗?

标签: c# wcf linq entity-framework wcf-data-services


【解决方案1】:

请记住,WCF 服务不能返回接口类型!它们需要是具体的 DataContract-ed 类型。尤其是 IQueryable,因为 IQueryable 对象实际上是“如何调用数据”而不是实际数据。

尝试返回一个列表:

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

编辑

显然您可以返回 IEnumerable,但不能返回 IQueryable。鉴于我对 IQueryable 的解释,这是有道理的。

【讨论】:

  • 谢谢文森特,就是这样。我的 Service Op 是基于 Scott Hanselman 的帖子(上面的更新中提到的)。事实上,网络上到处都是返回 IQueryable 的示例。呃……
  • 文森特,我想将您的答案标记为正确,但我认为您需要详细说明一件事。在对您的答案进行研究后,我发现这可能有点误导。您可以将返回类型设置为接口类型,但不能设置为 IQueryable。例如, IEnumerable 很好。只需将 IQueryable 换成 IEnumerable,一切正常。您不需要 List 或显式转换 .ToList()。再次感谢您让我走上正确的道路。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多