Change
var toRemove = firstCollection.Where(item => secondCollection.All(x =>
x.Key != item.Key));
to
var toRemove = firstCollection.Where(item => secondCollection.All(x =>
x.Key != item.Key)).ToArray();As it stands, your code is lazily iterating toRemove; as soon as something's removed from it, you'll get exception you described. This is not related to NHibernate, it's a standard 'feature' of .NET :). /Pete -----Original Message----- From: [email protected] on behalf of Matteo Migliore Sent: Thu 7/4/2013 11:58 AM To: [email protected] Subject: [nhusers] Modify the collections of an entity "collection was modified" exception Hi, I obtain the error "Collection was modified; enumeration operation may not execute." when I try to save (merge) a loaded entity. I use AutoMapper to write the values from the DTO (command) to the loaded entity and this method to synchronize the collection between the entity and the command: public static ICollection<TFirst> Synchronize<TFirst, TSecond>( this ICollection<TFirst> first, IEnumerable<TSecond> second, Func<TSecond, TFirst> convert = null, Func<TFirst, int> firstHash = null, Func<TSecond, int> secondHash = null) { if (firstHash == null) { firstHash = x => x.GetHashCode(); } if (secondHash == null) { secondHash = x => x.GetHashCode(); } if (convert == null) { convert = x => Mapper.Map<TFirst>(x); } var firstCollection = first.ToDictionary(x => firstHash(x), x => x); var secondCollection = second.ToDictionary(x => secondHash(x), x => x); var toAdd = secondCollection.Where(item => firstCollection.All(x => x.Key != item.Key)).Select(x => convert(x.Value)); foreach (var item in toAdd) { first.Add(item); } var toRemove = firstCollection.Where(item => secondCollection.All(x => x.Key != item.Key)); foreach (var item in toRemove) { first.Remove(item.Value); } return first; } How can I fix the problem? Thanks, Matteo -- You received this message because you are subscribed to the Google Groups "nhusers" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To post to this group, send email to [email protected]. Visit this group at http://groups.google.com/group/nhusers. For more options, visit https://groups.google.com/groups/opt_out. -- You received this message because you are subscribed to the Google Groups "nhusers" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To post to this group, send email to [email protected]. Visit this group at http://groups.google.com/group/nhusers. For more options, visit https://groups.google.com/groups/opt_out.
<<winmail.dat>>
