tags:

views:

31

answers:

1

I was wondering about the possibility of two things:

  1. Is it possible to use a WCF Data Service to expose "collections" that do not exist in the Entity Model (EDMX) that it is mapped to? Would this be a case where interceptors would make sense?

  2. How would one go about creating a WCF RESTful service without having to install the WCF Rest Starter Kit or using the "in the box" libraries on an ASP.NET 4 project? I ask because all the work we do is pushed to a production server where we won't have the luxury of installing a starter kit or additional software without a big hassle.

+1  A: 

The answer to both questions is breathtakingly simple. Given a WCF Data Service, create a method returning your IEnumerable<T> and use the [WebGet] attribute to expose it from the service.

Here is a step by step:

  1. Assume one has a Entity Data Model or Linq To Sql model exposing a datacontext called MyDBDataContext.

  2. The code for your WCF Data Service would look like the following:

    public class MyWCFDataService : DataService< MyDBDataContext >
    {
    
    
    
    // This method is called only once to initialize service-wide policies.
    public static void InitializeService(DataServiceConfiguration config)
    {
        // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
        // Examples:
        config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
        config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
        config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
    }
    
    }
  3. Assume you have some entity that is not in the model. In this case I'll use "Person" as an example:

    public class Person { public int PersonID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } }

  4. Simply add a method to your WCF Data Service class that returns your type and decorate it with [WebGet]:

public class CustomerDataServ : DataService< Data.CustDataClassesDataContext > {

[WebGet]
public IEnumerable<Person> GetEntries() {
    List<Person> entries = new List<Person>();
    for (int i = 0; i < 30; i++) {
        entries.Add(
            new Person() { PersonID = i, FirstName = "First " + i, LastName = "Last " + i }
        );
    }   
    return entries.ToArray();   
}

// This method is called only once to initialize service-wide policies.
public static void InitializeService(DataServiceConfiguration config)
{
    // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
    // Examples:
    config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
    config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
    config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
}

}

David in Dakota