0

I've a situation where I needed to duplicate/clone an entity record resulting in a new record in the database?

I've tried the following code but getting the error as

Collection was modified; enumeration operation may not execute.

This is the code I've tried

 var _dbWalkInn = _db.StudentWalkInns
                             .Where(r => r.Id == regId)
                             .FirstOrDefault();

if (_dbWalkInn != null)
{
   var _newWalkInn = new StudentWalkInn();
   var propInfo = _dbWalkInn.GetType().GetProperties();
   foreach (var item in propInfo)
   {
      _newWalkInn.GetType().GetProperty(item.Name).SetValue(_newWalkInn, item.GetValue(_dbWalkInn, null), null);
   }
   _newWalkInn.Id = 0;
   _db.StudentWalkInns.Add(_newWalkInn);
   _db.SaveChanges();
}

How can I duplicate/clone the entity ??

ksg
  • 3,927
  • 7
  • 51
  • 97
  • Is this being done in a loop? Normally this type of error is associated with modifying a collection while looping through it. – momar May 17 '16 at 10:44
  • Here the studentwalkinn has reference to studentwakinncourse which is having `1-n` relationship.Is that could be the reason? – ksg May 17 '16 at 10:58
  • You don't need a clone object. If you detach `_dbWalkInn` from the context and then `Add()` it, it's also duplicated. – Gert Arnold May 17 '16 at 11:03
  • @GertArnold I didnt get you?An example would be highly helpful? – ksg May 17 '16 at 11:05
  • 1
    Just get `_dbWalkInn` with `AsNoTracking()` and do `_db.StudentWalkInns.Add(_dbWalkInn);` A more complex example is [this](http://stackoverflow.com/a/36896133/861716). – Gert Arnold May 17 '16 at 11:11
  • Thanks mate for your help it worked. :) – ksg May 17 '16 at 11:57

0 Answers0