public Invoice GenerateInvoiceForByer(int byerId, List <OrderLine> orderLines) { Invoice newInvoice = null; try { var byerProfile = _userRepository.GetProfile(byerId); if (byerProfile != null) { var invoiceToSave = new Invoice { InvoiceNumber = GenerateInvoiceNumber(), ProfileID = byerProfile.ProfileID, CompanyName = byerProfile.CompanyName, SalutationID = byerProfile.SalutationID, FirstName = byerProfile.FirstName, LastName = byerProfile.LastName, Address = byerProfile.Address, PostalCode = byerProfile.PostalCode, City = byerProfile.City, CountryID = byerProfile.CountryID, InvoiceTotal = orderLines.Sum(ol => ol.Price) }; // save invoice to database and update the associated orderlines invoiceToSave = _orderRepository.SaveInvoice(invoiceToSave); if (invoiceToSave != null && _orderRepository.AddInvoiceIdToOrderLines(invoiceToSave.InvoiceID, orderLines)) { // reload invoice to retrieve all data of the created invoice newInvoice = _orderRepository.GetInvoiceAndContext(invoiceToSave.InvoiceID); } } } catch (Exception ex) { Logger.ErrorFormat("GenerateInvoiceForByer - error [{0}] - - \r\n {1} \r\n\r\n", ex.Message, ex.StackTrace); } return(newInvoice); }