Search code examples
linqrestwcf-data-services

How do I add a simple count to a WCF Data Service


I have a simple WCF Data Service set up. I went with a Linq-to-SQL solution.

public class MyDataService : DataService<SomeDataContext>
{
        public static void InitializeService(DataServiceConfiguration config)
        {
            config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
            config.SetEntitySetPageSize("*", 20);
            config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
        }

Since I'm using Linq, I had to do add partial classes for the keys

[DataServiceKey("MessageId")]
public partial class Message
{
}

[DataServiceKey("UserId")]
public partial class User
{
}

...

So I want to add a primitive method to get special users who have sent a message. Since Linq aggregate operators, such as count, are not supported, I figured a decent workaround would be to create a read-only resource endpoint for the count.So I added a method

   [WebGet]
    public int NumSpecialUsers()
    {
        var context = new SomeDataContext();
        int numUsers =
            context.Messages
            .Where(x => x.special == true && x.UserId != null)
            .Select(x => x.UserId)
            .Distinct()
            .Count();

        return numUsers;
    }

and added the necessary configuration to InitializeService()

    config.SetServiceOperationAccessRule("NumUsers", ServiceOperationRights.AllRead);

I can successfully call the method via localhost:1234/MyDataService.svc/NumSpecialUsers , however there's no discovery for this method in localhost:1234/MyDataService.svc. This doesn't seem right. By not showing up in localhost:1234/MyDataService.svc , that would violate REST, because it would mean an undiscoverable endpoint. Which also means that when you use Visual Studio to create an OData Linq proxy, it doesn't show the method there, either.

I'm neither a REST | OData | WCF Data Services expert, so if anyone has thoughts about this, I'd love to hear them. I am just beginning my adventure into OData and WCF Data Services and I would like to take a good approach to things. Many Thanks.


Solution

  • The problem is that for service operations to show in the service document, what will be the url look like if the service operations take parameters?

    We had a choice of showing none of the service operations or showing only service operations which take no parameters - we erred on the side of consistency and made the former choice.

    If you still think it would be better to show only service operations which take no parameters, then i would love to hear the argument and even make the change if we get a lot of feedback for this feature.

    Thanks Pratik