I’m saving an Order object using the following code:
public void SaveOrder (string orderNo)
{
using (var se = new StoreEntities)
{
var order = new Order { OrderNumber = orderNo }
try
{
//// Update
if (se.Orders.Any(e => e.OrderNumber == orderNo))
{
se.Orders.Attach(order);
se.ObjectStateManager.ChangeObjectState(order, EntityState.Modified);
}
//// Create
else
{
se.Orders.AddObject(order);
}
se.SaveChanges();
}
catch (OptimisticConcurrencyException){
se.Refresh(RefreshMode.ClientWins, order);
se.SaveChanges();
}
}
}
This works fine when it’s a new order and I’m just inserting into the DB.
However, if I’m trying to update an existing order, I get his error:
The following objects have not been refreshed because they were not
found in the store: ‘EntitySet=Orders;OrderID=0’.
In the database, the Order table looks like
OrderID | OrderNumber
13 567-87
15 567-93
where OrderID is an Identity key. There are no other rows besides these two as they have been deleted.
What am I doing wrong that I can’t update a record?
Looks like you’re getting the error because you’re attaching the new
Orderobject you’ve created as if it’s anOrderwhich already exists – that’s why theOrderIDin the error is zero.Try this:
Edit
You can update the order details property-by-property, or if you have an
Order(or anOrderViewModel, perhaps) with the details you want to update, you could use something like AutoMapper to copy the values for you.