I tried to insert Order Row with the Existing User using LINQ. The program should only insert the Order & Order Details because the User is already exist and I don't want to add the new user for each order.
Instead of that, the program is now inserting Order, OrderDetails together with User. So, I am getting duplicate users in my user table.
I iterate the cartitems and create the orderdetails rows and add them into Order table.
order o = new order() { orderDate = DateTime.Today};
foreach (CartItem ci in items)
{
orderdetail od = new orderdetail() { itemId = ci.ItemId, itemType = char.Parse(ci.ItemType), price = int.Parse(ci.Price.ToString()) };
o.orderdetails.Add(od);
}
user u = Users.GetUserByUserId(int.Parse(Session["userId"].ToString()));
Orders.AddOrder(o, u);
The below is how I add Orders
public static Boolean AddOrder(order o, user u)
{
try
{
u.orders.Add(o);
db.orders.InsertOnSubmit(o);
db.SubmitChanges();
return true;
}
catch
{
return false;
}
}
If I remove db.orders.InsertOnSubmit(o);, the database has no changes and no order is added to the database. If I add that line, it inserts both order, orderdetails and user data.
I am very new to LINQ and Please enlighten me, if you have any idea. Thanks.