ngeor.net | blog Proudly under construction since 2010 Subscribe Contact

Deferred LINQ queries in WCF services

12 Sep 2010 0 Comments

Consider the following WCF service:

WCF Service Interface

as you can see it defines one WCF service with two methods. The first method returns an IEnumerable of strings while the second method returns a class that contains an IEnumerable of strings.

The implementation I have looks like this:

WCF Service Implementation

The first method populates some sample data on a List and uses a LINQ query to return the data to the client. The second method calls the first method to populate its own results.

You would expect that they both work the same on the client. But they don't. The first method works fine, but the second one throws an obscure CommunicationException with the not so helpful message: The underlying connection was closed: The connection was closed unexpectedly. Here's what the WCF client looks like:

WCF client

To work around this, you need to force the evaluation of the LINQ query using the .ToArray or .ToList method. Then everything works normally. I'm not sure exactly why the deferred LINQ query works when the list is the direct return value and it fails when it is assigned to a data member of a class that is the returned value...

WCF Service fixed implementation

Categories: Tech

Pingbacks and trackbacks (2)+

Recent Comments

Comment RSS