Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Code First Deleting By ID Without Fetching (Generic Style)

Please tell me if this is a decent approach to deleting an Entity without fetching it given I have the ID.

I have a generic store with the following interface (I'll only show Delete):

public interface IStore : IReadOnlyStore
{
    void Delete<TEntity>(TEntity entity) where TEntity : class, IEntity, new();
    void SaveChanges();
}

And in the concrete Store class of that interface, here's my delete method:

public void Delete<TEntity>(TEntity entity) where TEntity : class, IEntity, new()
{
     var obj = Ctx.Entry(entity);
     if (obj.State ==  System.Data.EntityState.Detached)
     {
         Ctx.Set(typeof(TEntity)).Attach(obj.Entity);
     }
     Ctx.Set(typeof(TEntity)).Remove(obj.Entity);
}

I have tested both newing up an Entity:

Store.Delete(new Foo() { Id = request.Entity.Id });

as well as fetching an entity and then calling delete.

Through debugging, I have the desired affect on both scenarios.

I just want to make sure this is a good design and that there are no side effects to this approach.

For reference, Ctx is just the DbContext itself.

Thanks.

like image 659
Forest Avatar asked Oct 13 '11 15:10

Forest


1 Answers

It's good design and doesn't have side effects :) (IMHO)

Two remarks:

  • I'm wondering if you could simplify your Delete method by:

    public void Delete<TEntity>(TEntity entity) 
        where TEntity : class, IEntity, new()
    {
        Ctx.Entry(entity).State = EntityState.Deleted;
    }
    

    I would hope that setting the state to Deleted will attach automatically if the entity isn't already attached. But I am not sure if it works. (Let me know whether it works for attached and detached scenarios (if you should test this).)

  • If you have performance optimization in mind (avoiding to load the entities) don't forget that, if there are multiple entities to delete in the context, SaveChanges will still send one single DELETE statement per entity to the database. Bulk deletes with EF are quite terrible in performance and it's a terrain where going back to a SQL statements (DELETE ... WHERE ... IN ... many IDs....) sometimes makes sense (if performance matters).

like image 137
Slauma Avatar answered Oct 09 '22 18:10

Slauma