EF codefirst : Should I initialize navigation properties?

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

    The other answers fully answer the question, but I'd like to add something since this question is still relevant and comes up in google searches.

    When you use the "code first model from database" wizard in Visual Studio all collections are initialized like so:

    public partial class SomeEntity
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public SomeEntity()
        {
            OtherEntities = new HashSet();
        }
    
        public int Id { get; set; }
    
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection OtherEntities { get; set; }
    }
    

    I tend to take wizard output as basically being an official recommendation from Microsoft, hence why I'm adding to this five-year-old question. Therefore, I'd initialize all collections as HashSets.

    And personally, I think it'd be pretty slick to tweak the above to take advantage of C# 6.0's auto-property initializers:

        public virtual ICollection OtherEntities { get; set; } = new HashSet();
    

提交回复
热议问题