5,427,813 members and growing! (17,566 online)
Email Password   helpLost your password?
Web Development » Web Services » General     Intermediate License: The Code Project Open License (CPOL)

WCF and Linq

By Sam Haidar

A WCF web service that queries a database table using Linq, returning the resulting collection.
C# (C# 1.0, C# 2.0, C# 3.0, C#), .NET (.NET, .NET 3.5), ASP.NET, WCF, LINQ, Design, Architect, Dev

Posted: 22 Jul 2008
Updated: 22 Jul 2008
Views: 1,261
Bookmarked: 2 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
5 votes for this Article.
Popularity: 1.48 Rating: 2.11 out of 5
2 votes, 40.0%
1
1 vote, 20.0%
2
1 vote, 20.0%
3
0 votes, 0.0%
4
1 vote, 20.0%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Introduction

In this article, a web service with http binding is created, exposing a method that queries a database table using Linq. The method is defined in the service contract of the WCF service. Each resulting record from the Linq query is populated in an object that is defined in a data contract of the WCF service. The collection of objects are then returned by the service method as a generic IEnumerable collection.

Defining the WCF service

We first create the WCF service in Visual Studio 2008 and version 3.5 of .Net, using the wsHttp binding. The service is defined in the web.config file, as follows:

   <services>
      <service name="SomeService" behaviorConfiguration="ServiceBehavior">
          <endpoint address=""  binding="wsHttpBinding" contract="ISomeService">
             ...

Note how the address attribute of the endpoint is left blank for now, letting IIS use a default address. This can be changed to a fixed address at deployment time.

We then define the service contract in the ISomeService.cs file. The service contract is where all the service methods are defined:

    [ServiceContract]
    public interface ISomeService
    {
       [OperationContract]
       string GetData(int value);

       [OperationContract]
       IEnumerable<EmpRecord> GetEmpData(string empLastName);
    }

We have 2 methods defined, the first one is just a simple method that returns a string based on an int passed in as an argument. The second method, which is the one that is of real interest to us, accepts a last name of an employee and returns a collection of EmpRecord objects. The EmpRecord class is defined in the data contract of the service, also in the ISomeService.cs file, as follows:

    [DataContract]
    public class EmpRecord
    {
       int id = 0;
       string fName = "";
       string lName = "";
       string state = "";
       
      [DataMember]
      public int Id
      {
         get { return id; }
         set { id = value; }
      }
     
      [DataMember]
      public string First
      {
         get { return fName; }
         set { fName = value; }
      }
      
      [DataMember]
      public string Last
      {
         get { return lName; }
         set { lName = value; }
      }
      
      [DataMember]
      public string State
      {
         get { return state; }
         set { state = value; }
      }
    }

The EmpRecord class is defined as a data contract in the WCF service, with four private fields and four corresponding public properties to get and set the field values.

In the SomeService.cs file of the WCF project, we implement the service interface and methods that we defined above, as follows:

    public class SomeService : ISomeService
    {
       public string GetData(int value)
       {
           return string.Format("You entered: {0}", value);
       } 

       public IEnumerable<EmpRecord> GetEmpData(string empLastName)
       {
           LinqDataClassesDataContext ctxt = new LinqDataClassesDataContext();

           return from r in ctxt.Employees
                  where r.lName.Contains(empLastName)
                  select new EmpRecord { Id = r.ID, First = r.fName, Last = r.lName, State = r.state};
        }
     }

A Linq expression is used in the body of the GetEmpData method to query the Employee table, returning all rows that have their lName fields containing the last name string passed in as an argument. The Employee table is made up of the following fields: ID, fName, lName, City, and State. All matching rows are returned by the method as an IEnumerable collection. The LinqDataClassesDataContext is defined in the dbml file of our WCF service project, which is basically a Linq to SQL data context object. We created this data context object by visually dropping our database tables into the Linq to SQL dbml file that we added to our WCF project.

Consuming the WCF service

To consume the WCF service, we create an ASP.Net web application project, and add a service reference to it in the Solution Explorer. We then create an instance of the service and call the appropriate methods, such as:

    protected void Page_Load(object sender, EventArgs e)
    {
       SomeSvc.SomeServiceClient someSrvc = new SomeSvc.SomeServiceClient();
       var coll = someSrvc.GetEmpData("Evans");

       GridView2.DataSource = coll;
       GridView2.DataBind();

     }

SomeSvc is the name of the service reference that I added to my ASP.Net web app project, which gives us access to the client proxy class. I then call the GetEmpData method, passing an employee last name, and bind the returned collection of matching EmpRecord objects to a grid view.

Alternatively, we can just iterate throught the collection of EmpRecord objects, as shown below:

       bool bFound = false;
       foreach (SamSvc.EmpRecord empl in coll)
       {
          if (empl.State.IndexOf("FL") >= 0)
          {
             bFound = true;
             break;
          }
       }

Points of Interest

The simplicity of defining our own objects as data contracts in a WCF service, and making use of easy to use Linq expressions to encapsulate returned database records in those objects. Similarly, service contracts make it fairly straight forward to define our own methods in the WCF service, accepting and returning our own defined objects.

History

Initial post.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Sam Haidar


.Net developer in the South Florida area since 2000. Prior to .Net, mainly working with C++, MFC and COM.
Occupation: Software Developer (Senior)
Location: United States United States

Other popular Web Services articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 2 of 2 (Total in Forum: 2) (Refresh)FirstPrevNext
Subject  Author Date 
Generalwcf webservice with .net 2.0memberMember 32396613:10 4 Aug '08  
GeneralRe: wcf webservice with .net 2.0memberSam Haidar2:58 11 Aug '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 22 Jul 2008
Editor:
Copyright 2008 by Sam Haidar
Everything else Copyright © CodeProject, 1999-2008
Web07 | Advertise on the Code Project