Question

Refer to the EntityFramework article, and other ASP MVC webinars from Microsoft such as;

1: http://www.asp.net/mvc/videos/5-minute-introduction-to-aspnet-mvc

2: http://blogs.msdn.com/b/adonet/archive/2011/03/08/ef-feature-ctp5-code-first-model-with-master-detail-wpf-application.aspx

They use virtual keyword to reference between master and detail models.

Could you explain (1) why they use virtual keyword and (2) what drawbacks occur without the keyword?

Regards

Was it helpful?

Solution

They specify why in your second link:

When using POCO entity types, lazy loading is achieved by creating instances of derived proxy types during runtime and then overriding virtual properties to add the loading hook. To get lazy loading of related objects, you must declare navigation property getters as public, virtual (Overridable in Visual Basic), and not sealed (NotOverridable in Visual Basic). In the code above, the Category.Products and Product.Category navigation properties are virtual.

The only downside I can see is that, like any virtual method, these will perform ever so slightly slower than a non-virtual method. Chances are you will never be able to detect the performance difference.

You will see a delay in the first access of these properties, as lazy loading implies that the first read will result in a DB query.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top