Deferred Execution and Immediate Execution in LINQ

Deferred Execution executes the query only when Loop starts. What I mean here is that, we iterate through the query variable to get the result.
  

clip_image001

  

Here the result variable does not contain the actual result. To get the result, we may iterate through the result (query) variable in loop as many time as we want. We do deferred execution mainly when multiple values is being returned from the query.

  

Example

  


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
 class Program
 {
 static void Main(string[] args)
 {
 DataClasses1DataContext context = new DataClasses1DataContext();
 var result = from r in context.Persons select r;
 foreach (var a in result)
 {
 Console.WriteLine(a.FirstName + "" + a.LastName);
 }
 Console.ReadKey(true);

 }
 }
}

  

Output
clip_image003

  

Immediate Execution happens when LINQ query returns a single value.

  

clip_image005

  

Above query is returning a single value so it can be executed immediately.

  

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
 class Program
 {
 static void Main(string[] args)
 {
 DataClasses1DataContext context = new DataClasses1DataContext();
 var numberOfRecords = (from r in context.Persons select r).Count();
 Console.WriteLine(numberOfRecords);
 Console.ReadKey(true);

}
 }
}

  

Output
clip_image007

  

If we want to make a query returning multiple values or sequence of values as immediate then we need to explicitly convert the result in ToList().

  

clip_image009

  

So above query is returning multiple values and would be executed immediately.
Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace ConsoleApplication3
{
 class Program
 {
 static void Main(string[] args)
 {
 DataClasses1DataContext context = new DataClasses1DataContext();
 var result1 = (from r in context.Persons select r).ToList();
 foreach (var a in result1)
 {
 Console.WriteLine(a.FirstName + "" + a.LastName);
 }
 Console.ReadKey(true);
 }
 }
}
Output
clip_image011

Var versus IEnumerable in LINQ

We have seen normally
clip_image002
Or
clip_image004
Now question is where to use var or IEnumerable? Let us first have a look on both key words
Var derives type from the right hand side. And its scope is in the method. And it is strongly typed. IEnumerable is interface which allows forward movement in the collection.
Now in LINQ where to use what ?
If we really do not have idea that what would be the type of query then we will be using var. and if we are sure about the type of output then we would be using IEnumerable .
Using IEnumerable <T>
In the below example, we are querying in collection of string so we know the output would be collection of string, so we are using here IEnumerable with string.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq.Mapping;
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> lstStrings = new List<string> {"Dhananjay Kumar",
                                                         "Mahesh Chand",
                                                         "John papa",
                                                         "Mike Gold",
                                                         "Shiv Prasad Koirala",
                                                          "Victor ",
                                                           "Pinal Dave" };
            IEnumerable<string> result = from r in lstStrings select r;
            foreach (var r in result)
            {
                Console.WriteLine(r);
            }
            Console.ReadKey(true);
        }
    }
}

Output
clip_image006
Using var
Now if we don’t know exactly what would be the type of result in that case we will be using var. There might be some scenario where you want to return anonymous type from the query
clip_image008
If you see the above query we do not know the type of result.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq.Mapping;
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            DataClasses1DataContext context = new DataClasses1DataContext();
            var result = from r in context.Persons select new { NameOfperson = r.FirstName + r.LastName };
            foreach (var r in result)
            {
                Console.WriteLine(r.NameOfperson);
            }
            Console.ReadKey(true);
        }
    }
}

Output
clip_image010

Listing columns name with type of a table using LINQ

After my last post, I got a question asking how to list all the Column names of a given table using LINQ.

Before going through this post, I recommend you to read Get All the Tables Name using LINQ

Let us say, you have a table called dbo.Person and you need to find all the columns of this particular table. 
So first we need to find whether table exists in DataContext or not 

clip_image002

Dbo.Person is name of the table.
We are looking through all the tables and finding where given table exists or not. Once we get table we need to list the entire columns name
clip_image003

Full source code is as below. In below code we are finding whether dbo.Person table is existing or not. If existing in DataContext then listing all the columns name

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq.Mapping;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {

            DataClasses1DataContext context = new DataClasses1DataContext();
            var datamodel = context.Mapping;


            foreach (var r in datamodel.GetTables())
            {
                if (r.TableName.Equals("dbo.Person", StringComparison.InvariantCultureIgnoreCase))
                {

                    foreach (var r1 in r.RowType.DataMembers)
                    {
                        Console.WriteLine(r1.MappedName);
                    }
                }

            }
            Console.ReadKey(true);
        }
    }
}

Output
clip_image005

Get All the Tables Name using LINQ

We need to list all the table name of the DataContext.
This is very simple through LINQ mapping.
1. Add the namespace
clip_image001
2. Get the model from type of datacontext
clip_image003
DataClasses1DataContext is your datacontext class created by LINQ to SQL.
3. Use GetTables() method to list all the tables name
clip_image004

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq.Mapping;
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var datamodel = new AttributeMappingSource().GetModel(typeof(DataClasses1DataContext));
            foreach (var r in datamodel.GetTables())
            {
                Console.WriteLine(r.TableName);
            }
            Console.ReadKey(true);
        }
    }
}

Output
clip_image006
There is one more scenario. If you have already instance of DataContext and you want to list all the tables name then you need to get the model as below
clip_image007
Here context is instance of datacontext class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq.Mapping;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {

            DataClasses1DataContext context = new DataClasses1DataContext();
            var datamodel = context.Mapping;
            foreach (var r in datamodel.GetTables())
            {
                Console.WriteLine(r.TableName);
            }
            Console.ReadKey(true);
        }
    }
}

Output
clip_image009

WCF Service library: Creating, Hosting and consuming WCF service with WCF Service Library project template

In this article we will walkthrough on creating a WCF Service by choosing WCF Service Library project template.

Step 1

Create a WCF Service Library project.

clip_image002

Delete all the default codes created by WCF.

Step 2

Modify Operation Contract as below,

clip_image003

Implement the service as below

clip_image005

Step 3

Leave App.config file as it is with EndPoint with wsHttpBinding .

If needed, modify default port number to some other port to avoid getting run time exception while testing the service in WCF Service client.

clip_image007

Step 4

Now run the WCF service library. Just press F5. In WCF Test client service will be running.

clip_image009

Now we can see our service is tested and running in WCF Test client.

Step 5

Add a Web Application to the same solution. We will be hosting the WCF Service library to this web application.

clip_image011

Make web application project as startup project. To do so right click and make the project as start up project.

Step 6

Right click on the web application project and add reference of WCF Service library project , we created in step 1.

clip_image012

Step 7

Now right click on the Web Application project and from general tab add a text file. Give any name to the text file but make sure extension is .svc.

clip_image014

Add the below code in newly added .svc file.

clip_image016

In above code WcfServiceLibrary2 is the namespace of the service we created in step 1.

Step 8

Now we need to modify the Web.Config file of web application project and add the System.serviceModel .

clip_image017

We need to enable the Metadata exchange end point. So add below markup

clip_image019

Now add the service behavior to enable meta data exchange endpoint

clip_image021

And now add the service configuration behavior to the service. After adding that System.serviceModel will look like below

clip_image023

For reference config file will look like below,

Web.Config


<?xml version="1.0"?>

<!--
 For more information on how to configure your ASP.NET application, please visit
 <a href="http://go.microsoft.com/fwlink/?LinkId=169433">http://go.microsoft.com/fwlink/?LinkId=169433</a>
 -->

<configuration>
 <connectionStrings>
 <add name="ApplicationServices"
 connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
 providerName="System.Data.SqlClient" />
 </connectionStrings>

<system.web>
 <compilation debug="true" targetFramework="4.0" />

<authentication mode="Forms">
 <forms loginUrl="~/Account/Login.aspx" timeout="2880" />
 </authentication>

<membership>
 <providers>
 <clear/>
 <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
 enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
 maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
 applicationName="/" />
 </providers>
 </membership>

<profile>
 <providers>
 <clear/>
 <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
 </providers>
 </profile>

<roleManager enabled="false">
 <providers>
 <clear/>
 <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
 <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
 </providers>
 </roleManager>

</system.web>
 <system.serviceModel>
 <services>
 <service name ="WcfServiceLibrary2.Service1"
 behaviorConfiguration="WcfServiceLibrary2.Service1Behavior">
 <endpoint address =""
 binding ="wsHttpBinding"
 contract ="WcfServiceLibrary2.IService1" />
 <endpoint address="mex"
 binding="mexHttpBinding"
 contract="IMetadataExchange" />
 </service>
 </services>
 <behaviors>
 <serviceBehaviors>
 <behavior name="WcfServiceLibrary2.Service1Behavior">
 <serviceMetadata httpGetEnabled="True"/>
 <serviceDebug includeExceptionDetailInFaults="False" />
 </behavior>
 </serviceBehaviors>
 </behaviors>
 </system.serviceModel>
 <system.webServer>
 <modules runAllManagedModulesForAllRequests="true"/>
 </system.webServer>
</configuration>

 

Press F5 to run the service

clip_image025

Step 9

Now we will create a client to call the service. Right click on the same solution and add console project. Make console application as start project.

Add the service reference

clip_image026

Now call the service as below,

Programs.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ConsoleApplication1.ServiceReference1;

namespace ConsoleApplication1
{
 class Program
 {
 static void Main(string[] args)
 {

Service1Client proxy = new Service1Client();
 var r = proxy.GetMessage();
 Console.WriteLine(r);
 Console.ReadKey(true);
 }
 }
}

 

On running we will get the expected output as below,

clip_image028

WCF Data Service with LINQ to SQL Class

We have seen many articles and blogs talking about using WCF Data Service with ADO.Net Entity model generated class as model. In this article we are going to see, how to use WCF Data Service with LINQ to SQL Class.

There are three conditions while using LINQ to SQL class with WCF Data Service. One of below condition must be true

1. The Primary Key column of the table must have name ID.

2. Primary key column of the table must have ID appended to that. For example name of the column should be in the format EmpID, ProductID , RollNoID etc.

3. Third is, let us say you have to expose CRUD operation on your existing data base where you cannot change the existing columns. In that case follow the below steps

Step1

Launch visual studio and create a web application

Step2

a. Right click on the web application project and add data model using LINQ to SQL class.

clip_image002

b. Click on .cs file

clip_image003

c. Add the namespace System.Data.Services.Common on the class DataClasses1.designer.cs

d. Locate the entity class and put the DataServiceKey attribute

clip_image005

Above SpeakerId is name of the primary key column in the table Blogger.

Step 3

a. Right click on the Web Application project and add a new item by selecting WCF Data Service from Web Tab

clip_image007

b. Now provide the data class context name as the model.

clip_image009

Now we are done and we can run the WCF Data Service .