Reputation: 462
I have the following code:
Model
public class Orders
{
public int Id { get; set; }
public int UserId { get; set; }
public int ProductId { get; set; }
public int Quantity { get; set; }
public double Price { get; set; }
public bool OrderStatus { get; set; }
public string OrderNumber { get; set; }
public string AdminStatus { get; set; }
public bool PaymentStatus { get; set; }
public DateTime OrderDate { get; set; }
}
Controller
public ActionResult CheckOut()
{
if (Request.IsAjaxRequest())
{
var userid = WebSecurity.CurrentUserId;
var data = _bbdb.Orders.Where(x => x.OrderStatus == false && x.UserId == userid).ToList();
foreach (var item in data)
{
_bbdb.Orders.Add(new Orders
{
Id = item.Id,
UserId = item.UserId,
ProductId = item.ProductId,
Quantity = item.Quantity,
Price = item.Price,
OrderStatus = true,
OrderNumber = item.UserId + DateTime.Now.ToShortTimeString(),
AdminStatus = item.AdminStatus,
PaymentStatus = item.PaymentStatus,
OrderDate = DateTime.Today
});
_bbdb.SaveChanges();
}
}
var cartdata = GetCartItems();
return PartialView("_CartTable", cartdata);
}
How can I change this bit code _bbdb.Orders.Add(new Orders
to UPDATE instead ADD.
I thought something like _bbdb.Orders.AddOrUpdate(new Orders
would do the trick, but I does not exist.
It is adding the right value, but I want to update the records not add new ones.
Any suggestion on how to improve or change will be appreciated.
Upvotes: 0
Views: 2283
Reputation: 9881
Not sure how correct I am here, but try this...
_bbdb tracks the changes, so you simply need to get the item from the db, make the changes you need and then save them.
foreach (var item in data)
{
item.Price = 100; //Set whatever values you need to update
}
_bbdb.SaveChanges();
Also, notice that the SaveChanges()
method was moved outside of foreach
. The context will track the changes so you don't need to call SaveChanges
after each item is added.
Finally, I believe that you don't need ToList()
after the Where
-clause
Upvotes: 4