Attach and EntityState.Detached

entity-framework

Question

Why in this article: http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application we have check if EntityState.Detached in Delete method and then Attach and in Update method we don't have check:

    public virtual void Delete(TEntity entityToDelete)
    {
        if (context.Entry(entityToDelete).State == EntityState.Detached)
        {
            dbSet.Attach(entityToDelete);
        }
        dbSet.Remove(entityToDelete);
    }

    public virtual void Update(TEntity entityToUpdate)
    {
        dbSet.Attach(entityToUpdate);
        context.Entry(entityToUpdate).State = EntityState.Modified;
    }
1
3
7/21/2013 11:06:11 AM

Popular Answer

The reason the two are different is because in the tutorial there is another method which calls delete:

    public virtual void Delete(object id)
    {
        TEntity entityToDelete = dbSet.Find(id);
        Delete(entityToDelete);
    }

So if Delete(TEntity entityToDelete) was called from client side event - it should be attached 1st just like in the Update method, but if it was called from Delete(object id) as part of server side processing it will be already attached.

To be on the safe side: it is better to always check if it is attached before making changes, in specific: consider that in the future a revision might issue a server method that could invoke the Update method too in the same manner.

3
7/21/2013 11:23:49 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow