How to Work With Custom Method in WCF Data Service
In this article we will see how to expose a custom method in WCF Data Service.
In this article we will see how to expose a custom method in a WCF Data
Service. There are three steps involved in doing that:
- Create a partial class of Entity class and add desired custom method in that.
- Add a method with a WebGet attribute in the service class. This method will make a call to the custom method added in partial entity class.
- At the client side call custom method using Execute method.
Add Method in Partial Entity class
Create a partial class for the entity class. If you are working on a School database
and your entity class name is SchoolEntities then add one more partial class
along with custom method.
public partial class SchoolEntities
public string MyCustomMethod()
return "Hey I am returned from Custom Method ";
Modifying Service Class
Once you have added the custom method in the partial entity class, next you need to add a
method to the service class (.svc) with the WebGet attribute:
The above function creates an instance of the entity class and makes a call to the custom
method. The custom method will be called at the URL baseaddress/service.svc/CustomMethod.
Putting all together service class with one custom method will be as below:
public class WcfDataService1 : DataService<SchoolEntities>
// This method is called only once to initialize service-wide policies.
public static void InitializeService(DataServiceConfiguration config)
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
public string CustomMethod()
SchoolEntities entities = new SchoolEntities();
Calling custom method at client side
To call the custom method on the client side you need to make a call to the Execute method on an
instance of the Entity class. Execute is a generic method and it takes return type
of custom method as parameter. In this case return type of custom method is
string. Execute method returns IEnuramble. As the parameter to Execute method
you need to pass URI od custom method.
We can print the returned value from thecustom method from the WCF Data Service as below:
static void Main(string args)
SchoolEntities entities = new SchoolEntities
var result = entities.Execute<string>
foreach (var r in result)
Upon running of the above code you should be getting output as below:
In this way you can work with custom method in WCF Data service. I hope this
article is useful. Thanks for reading.