Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attach and EntityState.Detached

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;
    }
like image 221
michael Avatar asked May 16 '26 04:05

michael


1 Answers

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.

like image 182
G.Y Avatar answered May 19 '26 03:05

G.Y



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!