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.
Ok I understand what I was doing wrong now. I was using the following to select the entity from the context to model bind before it hits the controller action.
Instead of…
By detaching the entity, none of the navigation properties are loaded and therefore no changes can be made against them. Using AsNoTracking() still loads the navigation properties but also allows the entity object to be attached back for an update.
Hope this helps someone else in a similar situation.