Wednesday, January 16, 2013

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.


You must execute the query before detach it.

//this gets error

public IEnumerable<USER_CONTACT> SelectAll(Guid userId)
        {
            //create query
            var query = from q in unitOfWork.UserContacts
                        select q;

            foreach (var item in query)
            {
                unitOfWork.UserContacts.Detach(item);
            }
            return query;
        }


//no problem
public IEnumerable<USER_CONTACT> SelectAll(Guid userId)
        {
            //create query
            var query = from q in unitOfWork.UserContacts
                        select q;

            var result = query.ToList();
            foreach (var item in result)
            {
                unitOfWork.UserContacts.Detach(item);
            }

            return result;
        }

No comments:

Post a Comment