So my question basically has to do with nested models or associated tables (not sure the correct term). Specifically when TableA has an ICollection of TableB objects and TableB has an ICollection of TableA, how do I then save off my entire TableA model along with it's assocaited Table2 items.
For example:
User table with: string name, string address, ICollection < Orders >
Orders table with: OrderID, Total, ShipDate, ICollection < User >
So I have a User instance (UserA) which has the name and address set along with a collection of orders (Let's say Bob Dole, 1234 Main st, [567, $12.34, Oct 1; 999, $27.89, Nov 5;]). How do I trigger the save method to save both Orders & the User? My expectation would be "db.User.add(UserA); + db.SaveChanges();". I would expect this to save the User and upon seeing the Orders collection, save those as well.
However, previous developers did this:
User userB = db.User.Add(new User(userA.Name, userB.address)); //Why do we have to create a 2nd instance of a User object, that will hold the same information as userA?
foreach(Order order in userA.orders)
{
Order NewOrder = db.Orders.Add(order); //This now updates the Orders table with new info, which will be saved by 'db.SaveChanges()'
NewOrder.User.Add(userB); //How does this update the value in the Orders table with the userID? Isn't this updating the object about to go out of scope?
}
db.SaveChanges()
The only thing we can think, is the way they did it userB get's 'ID' assigned from the .Add command. But couldn't you simply say "userA = db.Users.Add(userA)" in order to update the instance with the ID provided upon database insert?