I have a DevExpress GridControl with rows from the database. The currently selected row is captured using a binding, and it's name is SelectedItem
.
I then try to edit the data for that row like so:
var entry = context.Entry(SelectedItem);
if (entry != null)
{
entry.Entity.Name = addForm.InstrumentName;
entry.Entity.InstrumentType = addForm.InstrumentType;
entry.Entity.Units = addForm.Units;
entry.Entity.RollOver = addForm.RollOver;
entry.State = EntityState.Modified;
try { context.SaveChanges(); }
catch (Exception ex)
{
//ex is of type DbUpdateConcurrencyException
}
}
However, if I use FirstOrDefault
to pull a fresh entity using just the SelectedItem.ID
, then I can make changes and save the record.
Now, I've been laboring under the idea that the former method is the preferred one for making changes to an entity, especially when that entity reference is already at hand. Am I wrong? If so, why?
If I'm not, then can someone help to explain why I might get a concurrency error?
Exception Details:
DbUpdateConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded.
Resulting Log Output (as requested):
UPDATE [dbo].[Instrument]
SET [EquipmentID] = @0, [Name] = @1, [InstrumentType] = @2, [Units] = @3, [RollOver] = @4
WHERE (([ID] = @5) AND [Timestamp] IS NULL)
SELECT [Timestamp]
FROM [dbo].[Instrument]
WHERE @@ROWCOUNT > 0 AND [ID] = @5
-- @0: '0' (Type = Int32)
-- @1: 'Hour meter' (Type = String, Size = 50)
-- @2: '0' (Type = Int32)
-- @3: 'hours1' (Type = String, Size = 25)
-- @4: '999999.00' (Type = Decimal, Precision = 18, Scale = 2)
-- @5: '2' (Type = Int32)
-- Executing at 4/26/2018 3:57:12 PM -04:00
-- Completed in 2 ms with result: SqlDataReader