DbUpdateConcurrencyException: Entities may have been modified or deleted since entities were loaded

c# entity-framework entity-framework-6

Question

i´m using EF6.

After i clear a tabel and i want to add a new entry to that table i get the following error:

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded

The code for deleting the databasetable:

 public void ResetStatistics() {
        _lisDatabase.Database.ExecuteSqlCommand("TRUNCATE TABLE Sortedtubes");
        _lisDatabase.sortedtubes.Local.Clear();
 }

After that i want to add a new entry to that table with the following code:

 Sortedtubes tube = new Sortedtubes();
 tube.Time = time;
 tube.Milliseconds = time.Millisecond.ToString();
 tube.Barcode = barcode;
 tube.Tubetype = tubeType;
 tube.Target = target;
 tube.Materialcode = materialCode;

 try {
        _lisDatabase.sortedtubes.Add(tube);
        _lisDatabase.SaveChanges(); // Error appears here
 } catch (DbUpdateConcurrencyException ex) {
        // maybe do something here?
 }

I tryed the sugestions on the EF documentation with no luck: https://msdn.microsoft.com/en-us/data/jj592904

EDIT

The problem seems to be the Clear() method (_lisDatabase.sortedtubes.Local.Clear();). After i execute this method the error appears after the next SaveChanges().

So maybe there is an other way to handle this? I have a GridView in my application witch is bind to the sortedtubes entity and i clear it so that the GridView is also cleared, when i truncat the table.

1
0
1/10/2018 9:32:01 AM

Popular Answer

So.. finaly i think i got a solution.

My reset method looks like this now:

public void ResetStatistics() {
     _lisDatabase.sortedtubes.RemoveRange(_lisDatabase.sortedtubes);
     _lisDatabase.SaveChanges();
}

And my add stays the same:

_lisDatabase.sortedtubes.Add(tube);
_lisDatabase.SaveChanges();

but the "big" change was in my Sortedtubes entity. I changed the type of Time from DateTime to a normal String

from:

[Key]
[Column(Order = 1)]
public DateTime? Time { get; set; }

to:

[StringLength(45)]
public string Time { get; set; }

The problem seems to be the Type of the Time property of the Sortedtubes Entity. But i don`t know why. If anyone wants to explain me this case?

Thanks to all for your help.

0
1/10/2018 2:44:05 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow