Monday, August 22, 2016

Entity Framework Code First - Don't Initialize Navigation Properties

At work we've been using Dapper.Net as our ORM.  For several months I felt that if we were using Entity Framework for our ORM our velocity would increase.  Recently my feelings on this have started to change as I've realized that Dapper doesn't suffer the restrictions of large ORMs.

Entity Framework is too much magic.  Let me provide the most recent example of that magic that wasted 3 hours of my life.

Code first gives us the ability to work with POCOs, which is nice.  Generally, when using EF I turn off lazy loading and proxy creation and I don't use virtual collections.  I new collections up in the constructor.  While I was doing that I also followed the law of least surprise.  Objects should be ready to use when created, so on a POCO I would also new up any child objects, such as the navigation property in the below example.  

//An example of what you should not do!
public class Contact  
   public Contact(){      
     PhoneNumbers = new List<PhoneNumber>();  
     Address = new Address();  
   public int Id { get; set; }  
   public string UserName { get; set; }  
   public List<PhoneNumber> PhoneNumbers {get; set; }  
   public Address Address { get; set; }  

Those of you that use EF all the time probably caught the above error.  Initializing the collection is fine, but initializing the navigation property is a problem.  It breaks EF's builtin relationship fix-up mechanism.  We've assigned an empty object to our navigation property and so now when trying to eager load the things we'll end up with an empty object instead of the expected entity from the db.

The rule then becomes, DO NOT new up navigation properties on your POCOs!  This is just a small example why I'm starting like Dapper more :)

No comments:

Post a Comment