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:
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. namespace WebApplication10 { 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: using System.Data.Services; using System.Data.Services.Common; using System.ServiceModel.Web; namespace WebApplication10 { public class WcfDataService1 : DataService<SchoolEntities> { // This method is called only once to initialize service-wide policies. public static void InitializeService(DataServiceConfiguration config) { config.SetEntitySetAccessRule("*", EntitySetRights.AllRead); config.SetServiceOperationAccessRule("*", ServiceOperationRights.All); config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2; } [WebGet] public string CustomMethod() { SchoolEntities entities = new SchoolEntities(); return entities.MyCustomMethod(); } } } 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: using System; using ConsoleApplication32.ServiceReference1; namespace ConsoleApplication32 { class Program { static void Main(string[] args) { SchoolEntities entities = new SchoolEntities (new Uri("http://localhost:2580/WcfDataService1.svc/")); var result = entities.Execute<string> (new Uri("http://localhost:2580/WcfDataService1.svc/CustomMethod")); foreach (var r in result) { Console.WriteLine(r.ToString()); } Console.ReadKey(true); } } } 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.
You need to be a premium member to use this feature. To access it, you'll have to upgrade your membership.
Become a sharper developer and jumpstart your career.
$0
$
. 00
monthly
For Basic members:
$20
For Premium members:
$45
For Elite members: