Search code examples
c#asp.net-mvcentity-frameworkrepositoryasp.net-mvc-4

Update on Entity fails using generic Repository


I have a generic repository:

    public class GenericRepository<TEntity> : AbstractRepository<TEntity>, IRepository<TEntity> where TEntity : class
    {
        private DbContext _context;
        [...]
        public GenericRepository(DbContext context)
        {
            _context = context;
            context.Configuration.AutoDetectChangesEnabled = true;
            _dbSet = _context.Set<TEntity>();
        }
        [...]
        public void SaveChanges()
        {
            _context.SaveChanges();
        }
        [...]
    public void Add(TEntity entity)
    {
        if (entity == null)
        {
            throw new ArgumentNullException("entity");
        }

        _dbSet.Add(entity);
    }
        [...]
    public virtual void Update(TEntity entity)
    {
        _context.Entry(entity).State = EntityState.Modified;
    }

In my controller, there is this code:

    [HttpPost]
    public ActionResult Edit(Project project)
    {
          if (ModelState.IsValid)
        {
            if (project.Id == 0)
            {
                ProjectRepository.Add(project);
            }
            else
            {
                ProjectRepository.Update(project);
            }

            ProjectRepository.SaveChanges();
            [...]

Selecting and Inserting works fine, but Updating not: I get an InvalidOperationException (english translation of the german error message is "An object with the same key already exists in the Object State Manager. The Object State Manager can not track multiple objects with the same key.").

I don't understand that, because I'm the only user on my development machine, and I did not modify the record at another place.

Any idea what I'm doing wrong here?


Solution

  • Take a look at these answers:

    Basically you need to do this:

     var entity = _context.Projects.Find(project.ProjectId);
     _context.Entry(entity).CurrentValues.SetValues(project);
    

    Hopefully this helps.