简体   繁体   中英

Entity Framework-Saving models with related tables

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?

First of all, I think, you've got to change your schema.

There will be one-to-many relationship between User and Orders . One user can have multiple orders but one order can not belong to multiple users. ie Only Order table would have UserId .

Update

Further, No need to add Orders data separately. As there would available collection type in the User table's entity.

You need to just assign values to the User table's entity along with Orders field and do insert it only once.

The code would be somehow as below:

var userData = user;
var orderData = orderCollection;

userData will be single record and orderData could be multiple.

Now assign that data to User data model:

var userAndOrder = new User
{
    Name = user.Name,
    Address = user.Address,
    Orders = orderCollection.Select(o => new Order
    {
        //assign order fields here
    }).ToList();
};

Then save this data. It will save Orders data itself in the Order table against the UserId.

db.Add(userAndOrder);
db.SaveChanges();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM