I’ve got an EntityFramework based database here created by code first approach. The database contains two tables with a parent-child-relationship between them:
Orderlists(based on model “Orderlist”)Orders(based on model “Order”)
where Orderlists contains an ICollection<Order> Orders which should (!) list all related orders. For some reason it doesn’t.
The DbContext of the controller contains two DbSets:
DbSet<Orderlist>DbSet<Order>
The model Order on the other hand has got two properties (with its type in brackets):
int OrderlistIdOrderlist OrderList
In the controller in a [HttpPost] Create method for a new Order object I’m wiring up this relation by picking the appropriate Orderlist object (with the correctly provided/selected ID) from the DbContext, setting OrderlistId and Orderlist of the newly created Order object appropriately and adding the Order to the Orders collection of the picked Orderlist (creating the collection if it is null).
Then I do a db.SaveChages(); which does what it’s supposed to do.
When the database is generated at first from the code of the models, regarding the relationship only the OrderlistId property generates a field in the datatables. Neither the Orders collection of the Orderlist nor the Orderlist property of the Order generate fields in the tables. That’s okay since it is still a valid relation: the ID of the Orderlist is a PK and the OrderlistId value is set correctly. The schemes of the datatables also reflect the relation by foreign keys.
Now, the problem is that the relation isn’t restored when processing the data at a different point in my application. The Orders ICollection is always null when I pick it from the DbContext.
My question is: should the Orders ICollection be filled automatically when creating the DbContext object? Or do I have to fill it manually by iterating through the Orders DbSet of the DbContext and add every appropriate Order manually to its related Orderlist? And, if I have to, where and how do I have to do that?
All association properties in Entity Framework Code First models must be marked with the virtual keyword, if you want Entity Framework to automatically load the associated entities on-demand (lazy-loading).
The following (basic) model definitions should work.
Also, note that when adding an Order to an OrderList, you don’t have to set the association properties on the Order entity. You can simply add the the new Order to the Orders collection on the OrderList entity, like this:
Alternatively, you could just set the OrderListId property on the new Order, and add it to the DbContext Orders collection.