Reputation: 11328
I was wondering if there is a good explanation somewhere as to when a Property will need to be instantiated in a model class constructor and when it is not necessary?
Docu on the MS EF site is good and covers a lot of related topics
Relationships and Navigation Properties - http://msdn.microsoft.com/en-us/data/jj713564
Configuring relationships with API http://msdn.microsoft.com/en-us/data/jj591620%20%22Configuring%20relationships%20with%20API
Entity Framework class library http://msdn.microsoft.com/en-us/library/hh289362%28v=vs.103%29.aspx
and im also part way through reading the Book Programming Entity Framework - Code First By Julia Lerman
I would like to better understand when a property needs to be instantiated in the Model constructor.
I see Samples in MS documentation and in the Book with and without newed up properties in the Model constructor.
There is most likely a good reason why some solutions use a constructor with newed Up objects and others not.
Seems like Virtual ICollection
has the new List<>
and complex type has new RefObj
.
But simple virtual navigation property
of type ModelObject are Ok without new.
Can I stick to a pattern without knowing the internals of each convention class. Or is there another topic I should be reading?
Upvotes: 1
Views: 532
Reputation: 3570
You never need to instantiate a property in the models constructor for EF to work, but it make it more convenient.
For example, If you had a class Order and it has children of Order Detail, and you wanted to add a new Order to your database.
Without initializing OrderDetails
var order = new Order();
order.OrderDetails.Add(new OrderDetail()); // this would error because OrderDetails is null
One option could be to call order.OrderDetails = new List(); before you use Add(), but then you would need to have that code repeated everywhere you wanted to use Add(). Instead you can put that code in the constructor, and then OrderDetails will be ready to use with all newly created Orders.
Upvotes: 1