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.
Update: I am basing some of my code (the ServiceOp, returning IEnumerable) off of Scott Hanselman's post here:
[WebGet]
public IQueryable<Post> GetPopularPosts()
I have setup a basic WCF DataService. As per the update bug, I defined it as:
public class Api : DataService<ObjectContext>
rather than as from TestDb. I setup the CreateDataSource() as:
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:
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:
An error occurred while processing this reques开发者_JS百科t. 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! They need to be concrete DataContract-ed types. Especially IQueryable since an IQueryable object is really a "how to call data" instead of actually data.
Try returning a List instead:
[WebGet]
public List<Stuff> GetStuff()
{
var context = new TestDb();
return context.Stuff.ToList();
}
EDIT
Apparently you CAN return IEnumerable, but not IQueryable. Which makes sense given my explanation of what IQueryable is.
精彩评论