EF codefirst : Should I initialize navigation properties?

前端 未结 6 1640
醉梦人生
醉梦人生 2020-11-22 09:24

I had seen some books(e.g programming entity framework code first Julia Lerman) define their domain classes (POCO) with no initialization of the navigation properti

6条回答
  •  广开言路
    2020-11-22 09:56

    It's redundant to new the list, since your POCO is depending on Lazy Loading.

    Lazy loading is the process whereby an entity or collection of entities is automatically loaded from the database the first time that a property referring to the entity/entities is accessed. When using POCO entity types, lazy loading is achieved by creating instances of derived proxy types and then overriding virtual properties to add the loading hook.

    If you would remove the virtual modifier, then you would turn off lazy loading, and in that case your code no longer would work (because nothing would initialize the list).

    Note that Lazy Loading is a feature supported by entity framework, if you create the class outside the context of a DbContext, then the depending code would obviously suffer from a NullReferenceException

    HTH

提交回复
热议问题