Search code examples
entity-frameworkprimary-keyvirtuallazy-loadingchange-tracking

Defining primary key as virtual in Entity Framework


What's the benefit of defining the primary key attribute as virtual in entity Framework?

AFAIK, virtual is used for lazy loading in navigation properties and for change tracking in other properties. But we don't need any of the mentioned features in primary keys.

So, Is it any use to define primary keys virtual?


Solution

  • Change tracking proxies are created only if all non-navigation mapped properties are virtual. MSDN:

    Each property that is mapped to a property of an entity type in the data model must have non-sealed (NotOverridable in Visual Basic), public, and virtual (Overridable in Visual Basic) get and set accessors.