Update Related Entity Of Detached Entity

Posted by Hemslingo on Stack Overflow See other posts from Stack Overflow or by Hemslingo
Published on 2012-11-01T16:59:23Z Indexed on 2012/11/02 11:00 UTC
Read the original article Hit count: 333

I'm having an issue updating an entity with multiple related entities. I've got a very simple model which consists of an article entity and a list of categories the article can be related to. You can choose from a check box list which of these categories are associated to it...which works fine.

The problem crops up when I actually come to update an existing entity using the dbContext. As I am updating this entity, I have already detached it from the context ready to re-attach it later so the update can execute properly.

I can see that after I posting the model, the category(s) are being added to the article entity just fine and it looks like it updates in the repository with no errors occurring.

When I look in the database the article has updated as normal but the category(s) have not.

Here is my (simplified) update code...

    public virtual bool Attach(T entity)
    {
        _dbContext.Entry(entity).State = EntityState.Modified;
        _dbSet.Attach(entity);

        return this.Commit();
    }

Any help will be much appreciated.

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about entity-framework