Collection was modified; enumeration operation may not execute. Exception

this code give me and Exception

Collection was modified; enumeration operation may not execute

i use Entity Framework to work with data

            foreach (OfflineMessage omc in _offMsgs)
            {

                var OimDB = new OimDBEntities();

                if (omc.MsgTo == e.MessageData.ToHeader.Uri)
                {
                    var offlineMessage = new OfflineMessage
                    {
                        Delivered = false,
                        MsgContent = omc.MsgContent,
                        MsgFrom = omc.MsgFrom,
                        MsgTime = omc.MsgTime,
                        MsgTo = omc.MsgTo,
                        ID = OimDB.OfflineMessages.NextId(f => f.ID)

                    };

                    oimRepository.InsertOIM(offlineMessage);

                    //InsertData(omc.MsgFrom, omc.MsgTo, omc.MsgContent, omc.MsgTime);
                }
            }
            _toHeader = e.MessageData.ToHeader.Uri;
        }

Answers


foreach (OfflineMessage omc in _offMsgs)
                {
                    if (omc.MsgTo == _toHeader)
                    {
                        _offMsgs.Remove(omc);
                    }
                }

You are removing elements from the collection while iterating over it. You can't do this. Instead of removing, add them to a temporary list, and after the foreach loop, Remove your items.


Need Your Help

dataCount graph filtered by a dimension

dc.js

I have a list of participants to various events as the data source

Table locking in ADO.NET

c# ado.net locking

is there a simple way to implement table locking in ADO.NET (without beeing dependend on a specific DBMS-feature)? I'm currently using TransactionScopes, but I'm not quite sure, whether they lock the