Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts

Tuesday, 12 April 2016

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 may in-process object or out-process object. Based on objects, 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 like as for, foreach.

  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.

Difference between Lazy Loading and Eager Loading

In LINQ and Entity Framework, you have Lazy Loading and Eager Loading for loading the related entities of an entity. In this article you will learn the differences between these two loading.


Lazy/Deferred Loading


In case of lazy loading, related objects (child objects) are not loaded automatically with its parent object until they are requested. By default LINQ supports lazy loading.

For Example:



  1. var query = context.Categories.Take(3); // Lazy loading

  2.  

  3. foreach (var Category in query)

  4. {

  5. Console.WriteLine(Category.Name);

  6. foreach (var Product in Category.Products)

  7. {

  8. Console.WriteLine(Product.ProductID);

  9. }

  10. }

Generated SQL Query will be:



  1. SELECT TOP (3)

  2. [c].[CatID] AS [CatID],

  3. [c].[Name] AS [Name],

  4. [c].[CreatedDate] AS [CreatedDate]

  5. FROM [dbo].[Category] AS [c]

  6. GO

  7.  

  8. -- Region Parameters

  9. DECLARE @EntityKeyValue1 Int = 1

  10. -- EndRegion

  11. SELECT

  12. [Extent1].[ProductID] AS [ProductID],

  13. [Extent1].[Name] AS [Name],

  14. [Extent1].[UnitPrice] AS [UnitPrice],

  15. [Extent1].[CatID] AS [CatID],

  16. [Extent1].[EntryDate] AS [EntryDate],

  17. [Extent1].[ExpiryDate] AS [ExpiryDate]

  18. FROM [dbo].[Product] AS [Extent1]

  19. WHERE [Extent1].[CatID] = @EntityKeyValue1

  20. GO

  21.  

  22. -- Region Parameters

  23. DECLARE @EntityKeyValue1 Int = 2

  24. -- EndRegion

  25. SELECT

  26. [Extent1].[ProductID] AS [ProductID],

  27. [Extent1].[Name] AS [Name],

  28. [Extent1].[UnitPrice] AS [UnitPrice],

  29. [Extent1].[CatID] AS [CatID],

  30. [Extent1].[EntryDate] AS [EntryDate],

  31. [Extent1].[ExpiryDate] AS [ExpiryDate]

  32. FROM [dbo].[Product] AS [Extent1]

  33. WHERE [Extent1].[CatID] = @EntityKeyValue1

  34. GO

  35.  

  36. -- Region Parameters

  37. DECLARE @EntityKeyValue1 Int = 3

  38. -- EndRegion

  39. SELECT

  40. [Extent1].[ProductID] AS [ProductID],

  41. [Extent1].[Name] AS [Name],

  42. [Extent1].[UnitPrice] AS [UnitPrice],

  43. [Extent1].[CatID] AS [CatID],

  44. [Extent1].[EntryDate] AS [EntryDate],

  45. [Extent1].[ExpiryDate] AS [ExpiryDate]

  46. FROM [dbo].[Product] AS [Extent1]

  47. WHERE [Extent1].[CatID] = @EntityKeyValue1

In above example, you have 4 SQL queries which means calling the database 4 times, one for the Categories and three times for the Products associated to the Categories. In this way, child entity is populated when it is requested.

You can turn off the lazy loading feature by setting LazyLoadingEnabled property of the ContextOptions on context to false. Now you can fetch the related objects with the parent object in one query itself.

  1. context.ContextOptions.LazyLoadingEnabled = false;

Eager loading


In case of eager loading, related objects (child objects) are loaded automatically with its parent object. To use Eager loading you need to use Include() method.

For Example



  1. var query = context.Categories.Include("Products").Take(3); // Eager loading

  2.  

  3. foreach (var Category in query)

  4. {

  5. Console.WriteLine(Category.Name);

  6. foreach (var Product in Category.Products)

  7. {

  8. Console.WriteLine(Product.ProductID);

  9. }

  10. }

Generated SQL Query will be



  1. SELECT [Project1].[CatID] AS [CatID],

  2. [Project1].[Name] AS [Name],

  3. [Project1].[CreatedDate] AS [CreatedDate],

  4. [Project1].[C1] AS [C1],

  5. [Project1].[ProductID] AS [ProductID],

  6. [Project1].[Name1] AS [Name1],

  7. [Project1].[UnitPrice] AS [UnitPrice],

  8. [Project1].[CatID1] AS [CatID1],

  9. [Project1].[EntryDate] AS [EntryDate],

  10. [Project1].[ExpiryDate] AS [ExpiryDate]

  11. FROM (SELECT

  12. [Limit1].[CatID] AS [CatID],

  13. [Limit1].[Name] AS [Name],

  14. [Limit1].[CreatedDate] AS [CreatedDate],

  15. [Extent2].[ProductID] AS [ProductID],

  16. [Extent2].[Name] AS [Name1],

  17. [Extent2].[UnitPrice] AS [UnitPrice],

  18. [Extent2].[CatID] AS [CatID1],

  19. [Extent2].[EntryDate] AS [EntryDate],

  20. [Extent2].[ExpiryDate] AS [ExpiryDate],

  21. CASE WHEN ([Extent2].[ProductID] IS NULL) THEN CAST(NULL AS int)

  22. ELSE 1 END AS [C1]

  23. FROM (SELECT TOP (3) [c].[CatID] AS [CatID], [c].[Name] AS [Name], [c].[CreatedDate] AS [CreatedDate]

  24. FROM [dbo].[Category] AS [c] )

  25. AS [Limit1]

  26. LEFT OUTER JOIN [dbo].[Product] AS [Extent2]

  27. ON [Limit1].[CatID] = [Extent2].[CatID]) AS [Project1]

  28. ORDER BY [Project1].[CatID] ASC, [Project1].[C1] ASC

In above example, you have only one SQL queries which means calling the database only one time, for the Categories and the Products associated to the Categories. In this way, child entity is populated with parent entity.
What do you think?

I hope you will enjoy the tips while programming with LINQ and Entity Framework. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Tuesday, 5 April 2016

Lambda Expression

What is Lambda Expression?




Lambda expression is one of the features introduced in the C# 3.0. Lambda expression helps you to ease the burden of writing verbose Anonymous Methods. It is a new way to write anonymous method. Actually during compile time all lambda expressions are converted in anonymous method.




First of all this is the introduction of anonymous method for those who are not aware with anonymous method feature.

Anonymous Method


Anonymous method feature was introduced in C# 2.0. Anonymous methods are used to write methods inline without declaring a formal method. Normally anonymous methods are used for small methods which are not reused. Anonymous methods let you declare a method body without giving it a name. Behind the scenes, they exist as 'normal' methods; however, there is no way to explicitly call them in your code. Anonymous methods can only be created when using delegates and, in fact, they are created using the delegate keyword.

Let's have an example:

We have a function GetAgeList which returns age list having ages greater than equal to 22. Find function is used to search ages greater than equal to 22.
public List <int> GetAgeList()
{
    List<int> ageList = new List<int>();
    ageList.Add(20);
    ageList.Add(24);
    ageList.Add(22);
    ageList.Add(26);
    return ageList.Where(Find).ToList();
}
public static bool Find(int age)
{
    return (age >= 22);
}

You can perform this task by an anonymous method like:
public List<int> GetAgeList()
{
    List<int> ageList = new List<int>();
    ageList.Add(20);
    ageList.Add(24);
    ageList.Add(22);
    ageList.Add(26);
    return ageList.Where(delegate(int age)
        {
            return (age >= 22);
        }).ToList();
}

You don't need to create function "Find" which will be used only one time. Anonymous method saves some typing work.

Now we will see how Lambda Expression makes this task easier.

Lambda Expressions


Lambda Expressions makes the thing even easier by allowing you to avoid writing anonymous method and statement block. Lambda Expressions are just a new way to write anonymous methods. At compile time all the lambda expressions are converted into anonymous methods according to lambda expression conversion rules.

Syntax


(parameters) => expression or statement block

The left side of the lambda operator "=>" represents the arguments to the method and the right side is the method body.

Different Types of Lambda Expressions


1. Expression Lambda


Expression lambda has only an expression on the right side of the lambda operator "=>"
(input parameters) => expression

num => num * num; //num is an integer and result of this expression will be num * num

2. Statement Lambda


Statement lambda has a statement block on the right side of the lambda operator "=>"
(input parameters) => {statement;}

num => { return num * num; }; //num is an integer and result of this expression will be num * num

The body of a statement lambda can consist of any number of statements; however, in practice there are typically no more than two or three.
For the age list example the code using lambda expression will be written like:
public List<int> GetAgeList()
{
    List<int> ageList = new List<int>();
    ageList.Add(20);
    ageList.Add(24);
    ageList.Add(22);
    ageList.Add(26);
    return ageList.Where(age => age >= 22).ToList();
}

Advantages of Lambda Expression



  1. It reduces typing effort. We don't need to specify the name of the function, its return type, and its access modifier.

  2. When reading the code you don't need to find for the method's definition.

Lambda expressions should be short. A complex definition makes the calling code difficult to read.

Some Important Points about Lambda Expression



  1. Variables defined within a lambda expression are accessible only within the scope of the lambda expression body.

  2. Jump statements (break, goto, continue) are not allowed within anonymous method/lambda expression.

  3. Lambda expressions themselves do not have type.

  4. As lambda expressions do not have any type so lambda expression cannot be assigned to an implicitly typed local variable.