I've written this ActionResult
to model an Order that goes through. I couldn't think of another way to write this without using context Db<Sets>
. It runs kinda slow, taking around 4 seconds to complete. Is there way to optimize the code or is this kinda has to happen since I'm doing so many inserts?
public ActionResult New(CustomerOrderModel model)
{
ViewBag.LimitNotExceeded = checkLimit();
if (ModelState.IsValid)
{
int prepaid;
int userIdLoggedIn = WebSecurity.CurrentUserId;
try
{
//
//Add Customer
using (var ctx = new CustomerContext())
{
ctx.CustomerInfos.Add(model.CustomerModel);
ctx.SaveChanges();
}
//
//Add Order
model.OrderInfo.UserProfileUserID = userIdLoggedIn;
model.OrderInfo.Customer_id = model.CustomerModel.id;
model.OrderInfo.DateCreated = DateTime.Now.ToLocalTime();
using (var ctx = new OrdersContext())
{
ctx.OrderInfos.Add(model.OrderInfo);
ctx.SaveChanges();
}
//
//Add Code
key = "s121sd";
KeyCode TheKey = new KeyCode();
TheKey.code = key;
TheKey.Customer_id = model.CustomerModel.id;
TheKey.nif = model.CustomerModel.nif;
TheKey.UserProfileUserId = userIdLoggedIn;
TheKey.DateCreated = DateTime.Now.ToLocalTime();
using (var ctx = new CodesContext())
{
ctx.CodesInfos.Add(TheKey);
ctx.SaveChanges();
}
//
//Assign and Create debts
using (var ctx = new UsersContext())
using (var dbx = new DebtsContext())
{
prepaid = ctx.UserProfiles.Find(userIdLoggedIn).Prepaid;
if (prepaid > 0)
{
--prepaid;
string query = "UPDATE dbo.UserProfile SET Prepaid='" + prepaid + "' WHERE UserId='" + userIdLoggedIn + "';";
ctx.Database.ExecuteSqlCommand(query);
}
else
{
Debts NewDebt = new Debts();
NewDebt.paid = false;
NewDebt.DateCreated = DateTime.Now.ToLocalTime();
NewDebt.UserProfileUserId = userIdLoggedIn;
NewDebt.Order_id = model.OrderInfo.id;
dbx.DebtInfos.Add(NewDebt);
int debts = dbx.DebtInfos.Count(q => q.UserProfileUserId == userIdLoggedIn);
if (debts <= ctx.UserProfiles.Find(userIdLoggedIn).MaxDebt)
{
//
//Warn them when they reach their last
}
dbx.SaveChanges();
string query = "UPDATE dbo.UserProfile SET Prepaid='" + prepaid + "' WHERE UserId='" + userIdLoggedIn + "';";
ctx.Database.ExecuteSqlCommand(query);
}
}
//DateTime a = DateTime.FromBinary(model.OrderInfo.Timestamp);
return RedirectToAction("Index", "Home");
}
catch (DataException ex)
{
ViewBag.ChangeResult = ex;
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
}
return View(model);
}