1

I'm trying out the WCF Data Services in .NET with .FirstOrDefault() on the returned Queryable. But when checking with Fiddler it's still returning the whole set of objects. I have to do something wrong?

The code is really basic:

[OperationContract]
IQueryable<Note> Query();

[WebGet(UriTemplate = "")]
public IQueryable<Note> Query()
{
    return _source.OfType<Note>().AsQueryable<Note>();
}

Note note = _client.Query().FirstOrDefault();

This will still yield and transfer all notes over the network.

What have I missed?

Can I even use IQueryable and "remote LINQ" with a normal WCF Web Service?

I've found some examples where they were using a DataService(T) and a DataServiceContext locally as a client. I did try that to but I never got it to work at all.

The only thing I need is this "remote LINQ"-feature so I can query my web service via LINQ and not respond with all items when only, for instance, the first was requested.

Andreas Zita
  • 6,150
  • 4
  • 39
  • 104

2 Answers2

2

When you call FirstOrDefault() you are on the client side so you will receive the whole list and your client will filter it to get only the first one. If you want to download only the first element, you will need a special webMethod were you do the firstOrDefault on the server side.

[WebGet]
public Note QueryFirst()
{
    return _source.OfType<Note>().AsQueryable().FirstOrDefault();
}
Pascal Piché
  • 592
  • 2
  • 13
0

I have run into other problems using First() using the NETFx HttpEntityClient. It throws a NotSupportedException when using First().

OData does not support First, but does support Take or Skip.

This is what I ended up having to do:

Note note = _client.Query().Take(1).ToArray().FirstOrDefault();
joelnet
  • 11,551
  • 4
  • 32
  • 49
  • It's hard to imagine that this will work any differently than `First()` – Kirk Broadhurst Dec 04 '12 at 04:07
  • I'm using the NETFx HttpEntityClient which will throw a NotSupportedException if you try to use First(). First() is not supported by OData query. Since Take() and Skip() are supported by OData, you can use them instead. I can confirm that this code does work as expected. – joelnet Dec 06 '12 at 01:25