Using Linq Include

Posted by

Hello everyone, in this article, I will discuss the topic of Linq Include Using.

When using Entity Framework, you’ve probably come across the concepts of Eager Loading and Lazy Loading. Let me explain these concepts.

Lazy Loading: It is the default data loading method for the entity models we create. For example, suppose we have two entity models named Product and ProductDetail. When we query for Product, and we attempt to use the corresponding ProductDetail object, it will populate and load that object automatically. In summary, automatic loading is involved.

Eager Loading: If we want to use the Eager Loading feature while retrieving data from the database, we need to first deactivate the Lazy Loading feature.

context.Configuration.LazyLoadingEnabled = false;

After deactivating Lazy Loading, we include related objects in our queries when writing them. In fact, during the query process, we connect the entities to each other while writing the query, allowing us to perform a single retrieval operation.

To achieve this, we use the Include method to link the entities together.

Let’s go through an example of how to use the Include operation.

Firstly, we create two models, namely the Product and Category entity models.

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public DateTime CreateDate { get; set; }
    public virtual Category Category { get; set; }
}
public class Category
{
   public Category()
   {
       Products = new HashSet<Product>();
   }

   public int Id { get; set; }
   public string Name { get; set; }
   public DateTime CreateDate { get; set; }
   public virtual ICollection<Product> Products { get; set; }
}

We have created the Product and Category objects. Since they will be related, there is a Category object on Product, and a Product List on Category.

Now, let’s write our query to retrieve the list of products.

using (var context = new DemoDBContext())
{
   context.Configuration.LazyLoadingEnabled = false;

   var products = context.Products.Include("Category").ToList();

   foreach (var product in products)
   {
      Console.WriteLine(product.Name);
   }
}

As seen, we first set the LazyLoadingEnabled property to false. It would be better to include this operation inside the context file we created. I did it here for demonstration purposes. When we deactivate the LazyLoadingEnabled property, our Product object will show the Category object as null. However, when we use the Include method to retrieve our query, it will populate this object, and if we want to use the Category information, we can do it in this way. Inside the Include method, we need to specify the name of our Category object as it is in the Product object.

I hope this is helpful.

See you in the next article…

Leave a Reply

Your email address will not be published. Required fields are marked *