[OperationBehavior(TransactionScopeRequired = true)] // roll back if there is a problem public void SubmitPrintOrder(Entities.PrintOrder order) { using (var db = new PhotoStudioContext()) { db.Database.Log = Console.WriteLine; db.SubmitOrder(order); Console.WriteLine("Request: Order {0} for client {1} received, printing {2} photos", order.OrderId, order.CustomerName, order.OrderItems.Count()); } }
public int SubmitOrder(Entities.PrintOrder printOrder) { Order order = new Order(); foreach (var photo in printOrder.OrderItems) { var dbPhotoEntity = new Photo() { PhotoName = photo.Name, Id = photo.Id }; // This line is very important! // This line tells the DbContext that the photo entity already exist in the DB and that it should // be AWARE of it and track it, and set the state to unchanged (since I just add it to an order). // Without this line, the SaveChanges will add thoes photos to the DB, with new ID's, since for // the DB context they are new and does not exist in the DB. Entry(dbPhotoEntity).State = EntityState.Unchanged; order.Photos.Add(dbPhotoEntity); } order.CustomerName = printOrder.CustomerName; _Orders.Add(order); // use AddRange for more than one order return(SaveChanges()); }