imagine having a simple POCO for EF 4.1 Codefirst:
public class Product
{
// Native properties
[Key]
public Guid ID { get; set; }
// Navigation properties
public virtual Category Category { get; set; }
public virtual ICollection<Customer> Customers { get; set; }
public Product()
{
this.ID = Guid.NewGuid();
// Do I have to instantiate navigation properties in the constructor or not???
this.Category = new Category();
this.Customers = new List<Customer>();
}
}
What I couldn’t figure out so far is if I should instantiate complex navigation properties in the POCO’s constructor or not?
Seems like all my current code is working if I don’t instantiate, but I’m concerned that my code might cause problems in the future.
Are there any rules, best practices or any side effects?
Thanks for your ideas and tips!
You don’t need to instantiate
Category. Category is single entity which either exists or not – Product is not responsible for its creation. You can need to instantiateCustomersto empty list.The reason why it works now is because your context will wrap entities with dynamic proxy which will handle instantiation of you
Customerscollection. Because of that other code can access the collection without receivingNullReferenceException. This can change if you create instance ofProductin your code without using EF. In such case there will be no dynamic proxy and your collection will be null = you will have to instantiate it yourselves.