Lesson Wednesday

In the next lesson, we'll learn about creating relationships between objects using Entity. Before we do, though, we'll briefly cover the virtual modifier, which will allow us to use lazy loading with Entity.

The virtual modifier

Here's an example of the virtual modifier as it will be used in the next lesson:

public virtual ICollection<Item> Items { get; set; }

Here, we have an Items property with a getter and setter that we are declaring as virtual. But what exactly does virtual mean?

Declaring something as virtual tells our application that we reserve the right to override it. By default, all methods are not virtual, which means they can't be overridden.

The virtual modifier cannot be used with static, abstract, or private modifiers. In the code above, Items is public so it can be virtual.

Lazy Loading

Marking a property virtual allows the Entity Framework to use lazy loading. Lazy loading just means that Entity will only retrieve information that our code explicitly requires. Let's look at an example to see why this is important.

In the next lesson, we'll be adding a one-to-many relationship where a Category can have many Items. Let's say we want to get a Category's Description property. Without lazy loading, our application would also get all other information related to the Category in question, including all the Items associated with it. That is very inefficient, especially if a Category has thousands of Items associated with it and we really just need the Category's Description for now.

However, for lazy loading to work, Entity needs to create its own internal version of objects. In order to do this, it needs to override the properties that will be lazy loaded. This is why we need the virtual modifier.

If an object property containing objects related to it is not declared virtual, Entity cannot lazy load. Because it's considered far more efficient, we will continue using lazy loading and virtual properties when dealing with database relationships in Entity.

Configuring our Projects for Lazy Loading

To actually use lazy loading, we will need to add the proxies package from Entity Framework Core:

$ dotnet add package Microsoft.EntityFrameworkCore.Proxies -v 5.0.0

Lesson 33 of 36
Last updated more than 3 months ago.