Why is the virtual keyword used in the C # core parts model?

See EntityFramework and other Microsoft ASP MVC webinars for example:

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 a virtual keyword to link between primary and detailed models.

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

Hi

+6
source share
1 answer

They indicate why in your second link:

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

The only drawback that I see is that, like any virtual method, they will run so slightly slower than a non-virtual method. Most likely, you will never be able to detect a difference in performance.

You will see a delay in the first access to these properties, as lazy loading means that the first reading will lead to a database query.

+3
source

Source: https://habr.com/ru/post/895716/


All Articles