HI WELCOME TO Sirees
Showing posts with label linq. Show all posts
Showing posts with label linq. Show all posts

Difference between Deferred execution and Immediate execution

LINQ provides a common query syntax to query any data source. In a LINQ query, you always work with objects. The object might be in-memory of the program or remote object i.e. out memory of the program. Based on object, LINQ query expression is translated and executed.
There are two ways of LINQ query execution as given below:

Deferred Execution

In case of differed execution, a query is not executed at the point of its declaration. It is executed when the Query variable is iterated by using loop for, foreach etc.
  1. DataContext context = new DataContext();
  2. var query = from customer in context.Customers
  3. where customer.City == "Delhi"
  4. select customer; // Query does not execute here
  5.  
  6. foreach (var Customer in query) // Query executes here
  7. {
  8. Console.WriteLine(Customer.Name);
  9. }
A LINQ query expression often causes deferred execution. Deferred execution provides the facility of query reusability, since it always fetches the updated data from the data source which exists at the time of each execution.

Immediate Execution

In case of immediate execution, a query is executed at the point of its declaration. The query which returns a singleton value (a single value or a set of values) like Average, Sum, Count, List etc. caused Immediate Execution.
You can force a query to execute immediately of by calling ToList, ToArray methods.
  1. DataContext context = new DataContext();
  2. var query = (from customer in context.Customers
  3. where customer.City == "Delhi"
  4. select customer).Count(); // Query execute here
Immediate execution doesn't provide the facility of query re-usability, since it always contains the same data which is fetched at the time of query declaration.
What do you think?
I hope you will enjoy deferred and immediate while programming with LINQ. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Understanding Expression and Expression Trees

In .NET, Expression is an abstract class which contains static methods and inherited by various types (like ParameterExpression, MethodCallExpression, BinaryExpression etc.) to create expression tree nodes of specific types. Also all these expression-specific expression tree types are defined in System.Linq.Expressions namespace.

Expression Trees

Expression Trees was first introduced in C# 3.0 (Visual Studio 2008), where they were mainly used by LINQ providers. Expression trees represent code in a tree-like format, where each node is an expression (for example, a method call or a binary operation such as x < y). You can also convert expression trees into compiled code and run it. This transformation enables dynamic modification of executable code as well as the execution of LINQ queries in various databases and the creation of dynamic queries.

Creating Expression Trees

  1. Using Expression Lambda

    The easiest way to generate an expression tree is to create an instance of the Expression<T> type, where T is a delegate type, and assign a lambda expression to this instance. Let’s take a look at the code.
    1. // Create an expression using expression lambda
    2. Expression<Func<int, int, int>> expression = (num1, num2) => num1 + num2;
    3.  
    4. // Compile the expression
    5. Func<int, int, int> compiledExpression = expression.Compile();
    6.  
    7. // Execute the expression.
    8. int result = compiledExpression(3, 4); //return 7
    In this example, the C# compiler generates the expression tree from the provided lambda expression as shown below:
    1. //Create the expression parameters
    2. ParameterExpression num1 = Expression.Parameter(typeof(int), "num1");
    3. ParameterExpression num2 = Expression.Parameter(typeof(int), "num2");
    4.  
    5. //Create the expression parameters
    6. ParameterExpression[] parameters = new ParameterExpression[] { num1, num2 };
    7.  
    8. //Create the expression body
    9. BinaryExpression body = Expression.Add(num1, num2);
    10.  
    11. //Create the expression
    12. Expression<Func<int, int, int>> expression = Expression.Lambda<Func<int, int, int>>(body, parameters);
    This looks much more complicated, but this is what actually happens when you supply a lambda expression to an expression tree.
  2. Using Expression Tree API

    Expression class is used to create expression trees by using the API. In .NET Framework 4, the expression trees API also supports assignments and control flow expressions such as loops, conditional blocks, and try-catch blocks. By using the API, you can create expression trees that are more complex than those that can be created from lambda expressions. Using API, above code can be re-written as:
    1. //Create the expression parameters
    2. ParameterExpression num1 = Expression.Parameter(typeof(int), "num1");
    3. ParameterExpression num2 = Expression.Parameter(typeof(int), "num2");
    4.  
    5. //Create the expression parameters
    6. ParameterExpression[] parameters = new ParameterExpression[] { num1, num2 };
    7.  
    8. //Create the expression body
    9. BinaryExpression body = Expression.Add(num1, num2);
    10.  
    11. //Create the expression
    12. Expression<Func<int, int, int>> expression = Expression.Lambda<Func<int, int, int>>(body, parameters);
    13.  
    14. // Compile the expression
    15. Func<int, int, int> compiledExpression = expression.Compile();
    16.  
    17. // Execute the expression.
    18. int result = compiledExpression(3, 4); //return 7

Expression Tree Structure

The simple structure of an Expression<TDelegate> has four properties as given below:
  1. Body

    The body of the expression.
  2. Parameters

    The parameters of the lambda expression.
  3. NodeType

    The type of node in the tree
  4. Type

    The type of the expression.

IEnumerable<T> and IQueryable<T> and Expression Trees

In LINQ, a query expression is compiled to expression trees or to delegates, depending on the type that is applied to query result. The IEnumerable<T> type LINQ queries are compiled to delegates and IQueryable or IQueryable<T> queries are compiled to expression trees. In short, LINQ queries that execute in process are compiled into delegates while the queries that executes out of process are compiled into expression trees.
In LINQ, domain-specific queries (like LINQ to SQL, LINQ to Entity) are result into IQueryable<T> type. The C# and Visual Basic compilers compile these queries into code that builds an expression trees at runtime. Then query provider traverse the expression tree and translate it into a query language (like T-SQL) which is appropriate for that data source.
Consider the following LINQ to SQL query expression:
  1. var query = from c in db.Customers
  2. where c.City == "Delhi"
  3. select new { c.City, c.CompanyName };
Here, variable query that is returned by this LINQ query is of type IQueryable. Here is the declaration of IQueryable:
  1. public interface IQueryable : IEnumerable
  2. {
  3. Type ElementType { get; }
  4. Expression Expression { get; }
  5. IQueryProvider Provider { get; }
  6. }
As you can see, IQueryable contains a property of type Expression which holds the expression tree and represents data structure equivalent to the executable code found in a query expression. The IQueryProvider type property hold the LINQ provider (like LINQ to SQL, LINQ to Entity etc.) and based on LINQ provider query is translated into an appropriate query (like T-SQL query). The Type property represents the type of the element(s) that are returned when the expression tree is executed.
In this way, the above code is never actually executed inside your program. It is first translated into the following SQL statement and then executed on SQL Server side.
  1. SELECT [t0].[City], [t0].[CompanyName]
  2. FROM [dbo].[Customers] AS [t0]
  3. WHERE [t0].[City] = @p0

Expression Trees vs Lambda Expressions

A common misunderstanding is that expression trees are identical to lambda expressions. But this is not true since you can also create and modify expression trees by using API methods i.e. without using lambda expression syntax at all.
Also, every lambda expression cannot be implicitly converted into an expression tree. Only expression lambda is implicitly converted an expression tree and statement lambda i.e. multi-line lambda cannot be implicitly converted into expression tree.
What do you think?
I hope you will enjoy Expression Tree while playing with LINQ. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Create xml from database using LINQ

XML data is often used to transfer data from one application to another. Since XML is language independent, hence it is a good choice to use xml for transferring data between two different platform applications. In C#, it is easy to make xml from database by using LINQ to SQL and LINQ to XML.

Create XML from Database

Suppose we have below table in database. Now I want to make xml of all the products which have stock greater than 0. Here I am using LINQ Pad to query data from the database. It is a great tool to query data from database using LINQ to SQL, LINQ to XML, LINQ to Entity Framework.
  1. CREATE TABLE Product (
  2. ProductID int IDENTITY(1,1) NOT NULL,
  3. ProductName varchar(50) NOT NULL,
  4. Price float NOT NULL,
  5. Stock int NOT NULL
  6. )
  7. GO
  8. INSERT INTO Product (ProductName,Price,Stock)VALUES('P001',12.12,100)
  9. INSERT INTO Product (ProductName,Price,Stock)VALUES('P002',102.12,200)
  10. INSERT INTO Product (ProductName,Price,Stock)VALUES('P003',104.12,500)
  11. INSERT INTO Product (ProductName,Price,Stock)VALUES('P004',108.12,100)
  12. INSERT INTO Product (ProductName,Price,Stock)VALUES('P005',72.12,10)
  13. INSERT INTO Product (ProductName,Price,Stock)VALUES('P006',72.12,0)
  14. GO
  15. SELECT * FROM Product
Now, query the data from above table using LINQ. We can also save the output to xml file.
  1. //Export above xml to xmlfile
  2. XElement.Save(Server.MapPath(@"~/export.xml"));
Summary
In this article I try to explain how to create xml from database using LINQ with example. I hope after reading this article you will be able to create xml from database. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.