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

c# entity-framework entity-framework-6

Question

I'm using EF6.

I see the following error when attempting to add a new record to a table after clearing it:

An unexpectedly large number of rows were impacted by a store update, insert, or delete statement (0). Since entities were loaded, they could have undergone changes or been removed.

The following code will delete the database table:

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

Then, using the following code, I wish to add a new entry to that table:

 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?
 }

Without success, I tried the suggestions in the EF documentation: https://msdn.microsoft.com/en-us/data/jj592904

EDIT

The issue seems to be theClear() approach (_lisDatabase.sortedtubes.Local.Clear(); ). When I use this approach, an error follows the subsequentSaveChanges() .

Therefore, is there another way to approach this? When I truncate the table, I clear the GridView that is bound to the sortedtubes object in my application so that it is likewise cleaned.

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

Popular Answer

So, I believe I have an answer at last.

My current reset strategy is as follows:

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

And I continue to add:

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

nonetheless, my Sortedtubes entity underwent the "major" modification. I switched the Time's type from DateTime to a standard String.

from:

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

to:

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

The Type of the Time attribute of the Sortedtubes Entity seems to be the issue. But I'm not sure why. If somebody would want to clarify this situation to me?

I appreciate everyone's assistance.

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