Why virtual keyword is used in C# master-detail model?
Asked Answered
W

1

7

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

Wellspring answered 24/8, 2011 at 3:2 Comment(0)
K
4

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.

Keystone answered 24/8, 2011 at 3:30 Comment(2)
Thanks for your answer. One more question, is it still recommended if I do NOT need POCO-support or lazy loading?Wellspring
It certainly shouldn't hurt anything, but no, I don't think that it would be needed.Keystone

© 2022 - 2024 — McMap. All rights reserved.