I have an issue where I'm inserting a new record of order and inside of order i have order details. There can be multiple details each with a product which already exists in the database. My problem is when i try to update the order detail product with the product from the database it wants to put a new record into the database with an empty guid instead of using the one that is already there.
var order = context.Orders.FirstOrDefault(o => o.OrderId == request.Order.OrderId);
if (order == null)
{
...
// This is where a new order is mapped in from a class model
// The class model contains order information and order details.
...
// Order Detail
foreach (var detail in order.OrderDetails)
{
var product = context.Products.FirstOrDefault(p => p.ProductId == detail.Product.ProductId);
detail.Product = product;
detail.ProductId = product.Id;
}
context.SaveChanges();
}
I have tried to set the detail.Product state to unchanged but that does not work either.
Here is what the records look like after one order has been inserted. You can see the same ProductId but different Guid's. The one that has a Guid is the original that it found but after doing SaveChanges then the empty Guid record was inserted.
Id ProductId CostPrice DateCreated
00000000-0000-0000-0000-000000000000 11671170639 14.75 2017-07-08 04:16:21.927
931F65C2-919B-4876-8D6A-77387FF22001 11671170639 14.75 2017-07-07 11:11:29.327