I have a Windows desktop app with EF using a dbcontext and the change tracker. I am able to modify certain records to update datetime and modifiedby userid by iterating over a collection.
While it worked for some entries, a few other entries were throwing this error
System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
The code I have is below and it compiles fine
var changeSet = this.ChangeTracker.Entries();
foreach (var entry in changeSet)
{
if (entry.State == EntityState.Added || entry.State == EntityState.Modified)
{
if (entry.Entity is IAuditableEntity entity)
{
entry.Entity.ModifieDate = Now;
entry.Entity.ModifiedById = userId;//guid
}
}
}
// ModifiedById has a foreign key reference to Users table -> id field
// IAuditableEntity has ModifiedById and ModifiedDate fields
I tried converting to list but it throws an error it cannot convert to list. it worked for some models in the "this" context . The error was thrown only for one model.
Update:
copying the entries to a list and updating objects in the list does the job and there is no error. But I am wondering why it worked for few and not for others when I used this.ChangeTracker.Entries() with for each.
I have am using .NET Entity Framework 6 (EF6) to load parent/child data into a database.
A CVE is a 'parent' entity which has multiple children associated with it (for example "references", and "CVSS scores"). Once I have my context loaded with all the ojbects I want to save (CVEs and their associated children) I call "SaveChanges" and then want to know how many parent entities (CVEs) were inserted into the database.
Unfortunately the "SaveChanges" method returns the total number of objects added. I only want to know the number of CVE's (parent objects) added.
Here is my code;
internal static int LoadCVEs(IEnumerable<CVE> cves)
{
using (var context = new NVDEntities())
{
try
{
foreach(var cve in cves)
{
var existingCVE = context.CVEs.Find(cve.CveID);
//Check if CVE already exists.
if (existingCVE != null)
{
//Check to see if this record was recently modified. If so, then replace the entire record with the latest one.
if (DateTimeOffset.Compare(cve.ModifiedDate.Value, existingCVE.ModifiedDate.Value) > 0)
{
//CVE has been recently modified. Replace the outdated record.
context.CVEs.Remove(existingCVE);
context.CVEs.Add(cve);
}
}
else
{
//CVE is new. Insert it.
context.CVEs.Add(cve);
}
}
context.SaveChanges();
}
}
Among other things, I have tried the following;
context.CVEs.Where(c => context.Entry(c).State == EntityState.Added).Count()
But that returns the following error;
An unhandled exception of type 'System.NotSupportedException' occurred
in EntityFramework.SqlServer.dll
Additional information: LINQ to Entities does not recognize the method
'System.Data.Entity.Infrastructure.DbEntityEntry`1[NVDImport.Models.CVE]
EntryCVE' method, and this method cannot be
translated into a store expression.
How do I get the total count of CVEs (parent objects) that were added?
Maybe something like this?
In your DbContext inheriting class, you want to override your SaveChanges() method:
public override int SaveChanges()
{
int cveCount = ChangeTracker.Entries<CVE>().Where(argEntry => argEntry.State == EntityState.Added).Count();
base.SaveChanges();
return cveCount;
}
Update: Ahh! Dumb error: I had two instances of a Repository available, and, our implemntation requires that we provide a connection string for each Repo, so the two Repos were pointing to different databases, and I was adding an entity from one DB to another, and its id probably could not be found in the updated DB.
I'm running .Net MVC 4.0, with EF 5. We implement a repository pattern. In the following Delete method of a WebApi controller I have the following code:
int userID = UserHelper.GetCurrentUserID();
DateTime now = DateTime.UtcNow;
ExhibitLinkRepository el = new ExhibitLinkRepository();
el.setCase = caseID;
ExhibitLink link = el.All.SingleOrDefault(l => l.id == id);
//Mark Link Deleted
link.usermodified_id = userID;
link.datetimemodified = now;
link.deleted_flag = true;
exhibitLinkRepository.InsertOrUpdate(link);
exhibitLinkRepository.SaveChanges();
Where exhibitLinkRepository.InsertOrUpdate:
public void InsertOrUpdate(ExhibitLink exhibitLink)
{
if (exhibitLink.id == default(int))
{
// New entity
context.ExhibitLinks.Add(exhibitLink);
}
else
{
// Existing entity
context.Entry(exhibitLink).State = EntityState.Modified;
}
}
When I invoke context.SaveChanges() I get the dreaded:
Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.
Now, the ExhibitLink table has foreign key constraints as follows:
There happen to be triggers on the underlying DB for some of these related tables, but disabling them did not change the outcome.
I just don't get it. Any ideas?
I have problem with deleting related rows in Entity Framework 4.1. I have tables with relations
Book 1<--->* BookFormats
I have set the on delete cascade:
ALTER TABLE [dbo].[BookFormats] WITH CHECK ADD CONSTRAINT [FK_BookFormats_Book]
FOREIGN KEY([BookID]) REFERENCES [dbo].[Book] ([BookID]) on delete cascade
The EDMX property
Then, I want to remove the all BokFormats items related to my Book object:
var originalBook = m.db.Book.First(x => x.BookID == bookId);
originalBook.BookFormats.Clear();
m.db.SaveChanges();
But, I get the error:
The operation failed: The relationship could not be changed because
one or more of the foreign-key properties is non-nullable. When a
change is made to a relationship, the related foreign-key property is
set to a null value. If the foreign-key does not support null values,
a new relationship must be defined, the foreign-key property must be
assigned another non-null value, or the unrelated object must be
deleted.
I ran out of ideas on how to delete these objects. Any ideas?
You can use RemoveRange :
m.db.BookFormats.RemoveRange(originalBook.BookFormats);
m.db.SaveChanges();
But this is for EF 6.0
Cascade deletions concept is as follows:
When you delete Book from the DB all related BookFormats will be deleted for you by SQL Server (please note that it doesn't matter how deletion of Book will be initiated via EF or raw SQL). Thus it has nothing to do with your task: "I want to delete all BookFormats related to my Book". To accomplish it you need something like this:
foreach(var m in m.db.BookFormats.Where(f=>f.BookID == bookID))
{
m.db.BookFormats.Remove(m);
}
m.db.SaveChanges();
You are not deleting the BookFormats from the database, but you are removing the relationship, thus orpahning your BookFormats and setting the BookID column to NULL. The delete cascade you have put on the database says When I delete theBook, then delete all of theBookFormatsthat have aBookIDequal to mine. You are not deleting the book you are deleting the formats from the Book.
Instead of originalBook.BookFormats.Clear() you should have something like this...
List<int> idsToDelete = new List<int>();
foreach (BookFormat bf in originalBook.BookFormats)
{
idsToDelete.Add(bf.ID);
}
foreach (int id in idsToDelete)
{
BookFormat format = m.db.BookFormat.FirstOrDefault(x => x.ID == id);
if (format != null)
{
m.db.DeleteBookFormat(format);
}
}
m.db.SaveChanges();
It should be something along those lines. I don't have it right in front of me to remember how EF constructs the delete method in the EDMX.
I've tested it in EF 6.1.3 and this should work fine:
var originalBook = m.db.Book.First(x => x.BookID == bookId);
originalBook.BookFormats.Clear();
db.Books.Remove(originalBook);
m.db.SaveChanges();
I use EF6 and this works.
var itemBinding = db.ItemBinding.Where(x => x.BindingToId == id) ;
foreach (var ib in itemBinding)
{
db.Item.Remove(ib.Item);
db.ItemBinding.Remove(ib);
}
db.SaveChanges();
UPDATE (2010-12-21): Completely rewrote this question based on tests that I've been doing. Also, this used to be a POCO specific question, but it turns out that my question isn't necessarily POCO specific.
I'm using Entity Framework and I've got a timestamp column in my database table that should be used to track changes for optimistic concurrency. I've set the concurrency mode for this property in the Entity Designer to "Fixed" and I'm getting inconsistent results. Here are a couple of simplified scenarios that demonstrate that concurrency checking works in one scenario but not in another.
Successfully throws OptimisticConcurrencyException:
If I attach a disconnected entity, then SaveChanges will throw an OptimisticConcurrencyException if there is a timestamp conflict:
[HttpPost]
public ActionResult Index(Person person) {
_context.People.Attach(person);
var state = _context.ObjectStateManager.GetObjectStateEntry(person);
state.ChangeState(System.Data.EntityState.Modified);
_context.SaveChanges();
return RedirectToAction("Index");
}
Does not throw OptimisticConcurrencyException:
On the other hand, if I retrieve a new copy of my entity from the database and I do a partial update on some fields, and then call SaveChanges(), then even though there is a timestamp conflict, I don't get an OptimisticConcurrencyException:
[HttpPost]
public ActionResult Index(Person person) {
var currentPerson = _context.People.Where(x => x.Id == person.Id).First();
currentPerson.Name = person.Name;
// currentPerson.VerColm == [0,0,0,0,0,0,15,167]
// person.VerColm == [0,0,0,0,0,0,15,166]
currentPerson.VerColm = person.VerColm;
// in POCO, currentPerson.VerColm == [0,0,0,0,0,0,15,166]
// in non-POCO, currentPerson.VerColm doesn't change and is still [0,0,0,0,0,0,15,167]
_context.SaveChanges();
return RedirectToAction("Index");
}
Based on SQL Profiler, it looks like Entity Framework is ignoring the new VerColm (which is the timestamp property) and instead using the originally loaded VerColm. Because of this, it will never throw an OptimisticConcurrencyException.
UPDATE: Adding additional info per Jan's request:
Note that I also added comments to the above code to coincide with what I see in my controller action while working through this example.
This is the value of the VerColm in my DataBase prior to the update: 0x0000000000000FA7
Here is what SQL Profiler shows when doing the update:
exec sp_executesql N'update [dbo].[People]
set [Name] = #0
where (([Id] = #1) and ([VerColm] = #2))
select [VerColm]
from [dbo].[People]
where ##ROWCOUNT > 0 and [Id] = #1',N'#0 nvarchar(50),#1 int,#2 binary(8)',#0=N'hello',#1=1,#2=0x0000000000000FA7
Note that #2 should have been 0x0000000000000FA6, but it's 0x0000000000000FA7
Here is the VerColm in my DataBase after the update: 0x0000000000000FA8
Does anyone know how I can work around this problem? I'd like Entity Framework to throw an exception when I update an existing entity and there's a timestamp conflict.
Thanks
Explanation
The reason why you aren't getting the expected OptimisticConcurrencyException on your second code example is due to the manner EF checks concurrency:
When you retrieve entities by querying your db, EF remembers the value of all with ConcurrencyMode.Fixed marked properties by the time of querying as the original, unmodified values.
Then you change some properties (including the Fixed marked ones) and call SaveChanges() on your DataContext.
EF checks for concurrent updates by comparing the current values of all Fixed marked db columns with the original, unmodified values of the Fixed marked properties.
The key point here is that EF treats the update of you timestamp property as a normal data property update. The behavior you see is by design.
Solution/Workaround
To workaround you have the following options:
Use your first approach: Don't requery the db for your entity but Attach the recreated entity to your context.
Fake your timestamp value to be the current db value, so that the EF concurrency check uses your supplied value like shown below (see also this answer on a similar question):
var currentPerson = _context.People.Where(x => x.Id == person.Id).First();
currentPerson.VerColm = person.VerColm; // set timestamp value
var ose = _context.ObjectStateManager.GetObjectStateEntry(currentPerson);
ose.AcceptChanges(); // pretend object is unchanged
currentPerson.Name = person.Name; // assign other data properties
_context.SaveChanges();
You can check for concurrency yourself by comparing your timestamp value to the requeried timestamp value:
var currentPerson = _context.People.Where(x => x.Id == person.Id).First();
if (currentPerson.VerColm != person.VerColm)
{
throw new OptimisticConcurrencyException();
}
currentPerson.Name = person.Name; // assign other data properties
_context.SaveChanges();
Here is another approach that is a bit more generic and fits in the data layer:
// if any timestamps have changed, throw concurrency exception
var changed = this.ChangeTracker.Entries<>()
.Any(x => !x.CurrentValues.GetValue<byte[]>("Timestamp").SequenceEqual(
x.OriginalValues.GetValue<byte[]>("Timestamp")));
if (changed) throw new OptimisticConcurrencyException();
this.SaveChanges();
It just checks to see if the TimeStamp has changed and throws concurrency exception.
If it's EF Code first, then use code similar to below code. This will change the original TimeStamp loaded from db to the one from UI and will ensure OptimisticConcurrencyEception occurs.
db.Entry(request).OriginalValues["Timestamp"] = TimeStamp;
I have modified #JarrettV solution to work with Entity Framework Core. Right now it is iterating through all modified entries in context and looking for any mismatch in property marked as concurrency token. Works for TimeStamp (RowVersion) as well:
private void ThrowIfInvalidConcurrencyToken()
{
foreach (var entry in _context.ChangeTracker.Entries())
{
if (entry.State == EntityState.Unchanged) continue;
foreach (var entryProperty in entry.Properties)
{
if (!entryProperty.IsModified || !entryProperty.Metadata.IsConcurrencyToken) continue;
if (entryProperty.OriginalValue != entryProperty.CurrentValue)
{
throw new DbUpdateConcurrencyException(
$"Entity {entry.Metadata.Name} has been modified by another process",
new List<IUpdateEntry>()
{
entry.GetInfrastructure()
});
}
}
}
}
And we need only to invoke this method before we save changes in EF context:
public async Task SaveChangesAsync(CancellationToken cancellationToken)
{
ThrowIfInvalidConcurrencyToken();
await _context.SaveChangesAsync(cancellationToken);
}