Doing a shop project. Upon checkout, I create a list of all added product from cart and put it inside Order.Products
(M-M relationship):
List<Product> productList = Cart.Select(item => db.Products.SingleOrDefault(x => x.Id == item)).ToList();
var addOrder = new Order
{
Id = Guid.NewGuid(),
UserId = userId,
OrderDate = DateTime.Now,
Products = productList
};
db.Orders.Add(addOrder);
db.SaveChanges();
I debugged my code to make sure the productsList
had the right amount.
But after I added it, I only had one of each added products were added in my db. For e.g. if I have 3x cars, 4x books and 2x boat, then I just get one of each into M-M table, meaning total 3 products, even though I had total 9 in productList
.
This is how I set up my m-m relationship.
create table Product_Order (
ProductId uniqueidentifier foreign key references [Product](ID) not null,
OrderId uniqueidentifier foreign key references [Order](Id) not null
)
Btw, is it possible to add additional column into Product_Order
so called AmountProduct
, and set amount value instead making many rows of same products/order? If possible, how do I set amount value inside var addOrder = new Order{
? That way would probably be much more effective.