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 :)

Saturday, August 20, 2016

Pull Request /ˈedəkət,ˈedəˌket/

Over the years I've seen many unproductive threads on the net revolving around projects that are accepting pull requests.  In general when both project maintainers and contributors use their manners everyone stays happier.  When you read some project threads it often seems we aren't very kind to each-other.  Repudiate the code if you must, just don't offend the contributor.  That can be a difficult balance to strike!

The other day while reading in the Thinktecture.IdentityServer3 repo on GitHub, I found a list of links regarding pull request etiquette.  I found them so helpful I wanted to re-share them here.

Have you ever read a Linus Torvalds rant?  If you question whether or not you're interacting with your fellow coders correctly, read one of his rants and then NEVER do react like that!