EF codefirst : Should I initialize navigation properties?

前端 未结 6 1606
醉梦人生
醉梦人生 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:53

    Q1: Which one is better? why? Pros and Cons?

    The second variant when virtual properties are set inside an entity constructor has a definite problem which is called "Virtual member call in a constructor".

    As for the first variant with no initialization of navigation properties, there are 2 situations depending on who / what creates an object:

    1. Entity framework creates an object
    2. Code consumer creates an object

    The first variant is perfectly valid when Entity Framework creates a object, but can fail when a code consumer creates an object.

    The solution to ensure a code consumer always creates a valid object is to use a static factory method:

    1. Make default constructor protected. Entity Framework is fine to work with protected constructors.

    2. Add a static factory method that creates an empty object, e.g. a User object, sets all properties, e.g. Addresses and License, after creation and returns a fully constructed User object

    This way Entity Framework uses a protected default constructor to create a valid object from data obtained from some data source and code consumer uses a static factory method to create a valid object.

提交回复
热议问题