2

After a lot of hair pulling I've decided to join the stack overflow community and post my first question. When I try to update I get this error "entity cannot be referenced by multiple instances of IEntityChangeTracker".

Here's the IRepository.

public interface IRepository<T>
{
    void Update(T item);
}

And the Repository.

public class Repository<T> : IRepository<T> where T : class
{
    private readonly DbContext _dbContext;

    public Repository(DbContext context)
    {
        this._dbContext = context;
    }

    public virtual void Update(T item)
    {
        _dbContext.Entry(item).State = EntityState.Modified; // This is where the error happens
        _dbContext.SaveChanges();
    }
}

And Model class.

    Repository<Model> _model = new Repository<Model>(new ModelContext()); 

    public void Update(Model item)
    {
        this.Modified = DateTime.Now;

        _model.Update(item);
    }
}

And Model context.

public class ModelContext : DbContext
{
    public ModelContext()
        : base("name=DbContext")
    {
    }

    public DbSet<ModelContext> Model { get; set; }
}

And also the Controller

public class ModelController : Controller
{
    Model _model = new Model(); 

    public ActionResult Edit(int id, string name)
    {
        Model item = _model.GetById(id);

        if (Request.IsAjaxRequest())
        {
            item.Name = name;
            item.Update(item);
        }

        return View();
    }
}

And now it's the big question if some savior out there can make my day.

  • Hi, @Julius, no problem. Correct your question, please. –  Oct 30 '14 at 14:36
  • My Model has a typo in it. This should be like this. public DbSet Model { get; set; } I also found out what's causing the error. Having another ICollection in the DataAnnotations part for the Model causes the error. No solution yet though. – Julius Gudmundsson Oct 30 '14 at 14:37
  • I'll admit a little bit of confusion looking at some of the code. Do you have a Repository *inside* your Model class? Also, Does your `ModelContext` class really have a `DbSet` in it (that seems a little weird)? – Corey Adler Oct 30 '14 at 14:40
  • Add the `Model` in question and change the property of the `ModelContext` as I had said before. –  Oct 30 '14 at 14:41
  • Thanks all the solution is found. Since I have multiple dbsets because of related ICollections I needed to add this line _dbSet.Attach(item); before updating. Thank you all for your comments. – Julius Gudmundsson Oct 30 '14 at 14:49
  • IronMan84 is it a bad idea to have a referer at the top of the Model class for the generic Repository? – Julius Gudmundsson Oct 30 '14 at 14:50

0 Answers0