Reputation: 1
I have the following repository method :-
public void DeleteVM(int id, string username)
{
var VM = tms.TMSVirtualMachines.SingleOrDefault(a => a.TMSVirtualMachineID == id);
var auditinfo = IntiateTechnologyAudit(tms.AuditActions.SingleOrDefault(a => a.Name.ToUpper() == "DELETE").ID,
VM.Technology.TechnologyType.AssetTypeID,
username, VM.TMSVirtualMachineID);
var technology = tms.Technologies.SingleOrDefault(a => a.TechnologyID == id);
technology.IsDeleted = true;
tms.Entry(technology).State = EntityState.Modified;
var vm2 = VM;
foreach(var ip in vm2.Technology.TechnologyIPs)
{
tms.TechnologyIPs.Remove(ip);
}
tms.TMSVirtualMachines.Remove(VM);
InsertOrUpdateTechnologyAudit(auditinfo);
}
But i am getting the following exception :-
System.InvalidOperationException was caught HResult=-2146233079
Message=Collection was modified; enumeration operation may not execute. Source=System.Core StackTrace: at System.Collections.Generic.HashSet`1.Enumerator.MoveNext()
although i have created a copy of the VM and i perform the foreach over it..
Upvotes: 0
Views: 1258
Reputation: 22794
You need to do a shallow copy, not a reference copy. Even though you copy it over, you only copy the reference, so you're enumerating over the same HashSet
as the one you're deleting stuff from anyways.
What you need to do is construct another enumerable, like a List<T>
, over that. Like so:
var vm2 = new List<YourType>(VM.Technology.TechnologyIPs);
foreach(var ip in vm2)
{
tms.TechnologyIPs.Remove(ip);
}
Upvotes: 1