[英]WCF Data Service Operation cast issue
I am having a casting issue on returning what I thought was an IQueryable from a service operation, but apparently is a DbQuery. 我有一个关于从服务操作返回我认为是IQueryable的转换问题,但显然是DbQuery。
Update: I am basing some of my code (the ServiceOp, returning IEnumerable) off of Scott Hanselman's post here : 更新:我的一些代码(ServiceOp,返回IEnumerable)基于Scott Hanselman的帖子 :
[WebGet]
public IQueryable<Post> GetPopularPosts()
I have setup a basic WCF DataService. 我已经设置了一个基本的WCF DataService。 As per the update bug , I defined it as:
根据更新错误 ,我将其定义为:
public class Api : DataService<ObjectContext>
rather than as from TestDb. 而不是来自TestDb。 I setup the CreateDataSource() as:
我将CreateDataSource()设置为:
protected override ObjectContext CreateDataSource()
{
var testDb = new TestDb();
var objectContext = ((IObjectContextAdapter)testDb).ObjectContext;
objectContext.ContextOptions.ProxyCreationEnabled = false;
return objectContext;
}
In my InitializeService method, I call: 在我的InitializeService方法中,我调用:
config.SetServiceOperationAccessRule("GetStuff", ServiceOperationRights.AllRead);
And my service operation is: 我的服务操作是:
[WebGet]
public IQueryable<Stuff> GetStuff()
{
var context = new TestDb();
return context.Stuff;
}
The problem is that even though the method completes, and context.Stuff has items in it, the server returns an error: 问题是即使方法完成,并且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`
Any thoughts on this? 有什么想法吗?
Keep in mind that a WCF service cannot return interface types! 请记住,WCF服务无法返回接口类型! They need to be concrete DataContract-ed types.
它们需要是具体的DataContract-ed类型。 Especially IQueryable since an IQueryable object is really a "how to call data" instead of actually data.
特别是IQueryable,因为IQueryable对象实际上是“如何调用数据”而不是实际数据。
Try returning a List instead: 请尝试返回List:
[WebGet]
public List<Stuff> GetStuff()
{
var context = new TestDb();
return context.Stuff.ToList();
}
EDIT 编辑
Apparently you CAN return IEnumerable, but not IQueryable. 显然你可以返回IEnumerable,但不能返回IQueryable。 Which makes sense given my explanation of what IQueryable is.
鉴于我对IQueryable的解释,这是有道理的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.