title: Most efficiently handling Create, Update, Delete with Entity Framework Code First
body: <blockquote>
    <p><strong>Note:</strong> I am using Entity Framework version  5</p>
  </blockquote>
  
  <p>Inside my generic repository, I have <code>Add</code>, <code>Edit</code> and <code>Delete</code> methods as below:</p>
  
  <pre><code>public class EntityRepository&lt;T&gt; : IEntityRepository&lt;T&gt;
      where T : class, IEntity, new() {
  
      readonly DbContext _entitiesContext;
  
      public EntityRepository(DbContext entitiesContext) {
  
          if (entitiesContext == null) {
  
              throw new ArgumentNullException("entitiesContext");
          }
  
          _entitiesContext = entitiesContext;
      }
  
      //...
  
      public virtual void Add(T entity) {
  
          DbEntityEntry dbEntityEntry = _entitiesContext.Entry&lt;T&gt;(entity);
          if (dbEntityEntry.State != EntityState.Detached) {
  
              dbEntityEntry.State = EntityState.Added;
          }
          else {
  
              _entitiesContext.Set&lt;T&gt;().Add(entity);
          }
      }
  
      public virtual void Edit(T entity) {
  
          DbEntityEntry dbEntityEntry = _entitiesContext.Entry&lt;T&gt;(entity);
          if (dbEntityEntry.State == EntityState.Detached) {
  
              _entitiesContext.Set&lt;T&gt;().Attach(entity);
          }
  
          dbEntityEntry.State = EntityState.Modified;
      }
  
      public virtual void Delete(T entity) {
  
          DbEntityEntry dbEntityEntry = _entitiesContext.Entry&lt;T&gt;(entity);
          if (dbEntityEntry.State != EntityState.Detached) {
  
              dbEntityEntry.State = EntityState.Deleted;
          }
          else {
  
              DbSet dbSet = _entitiesContext.Set&lt;T&gt;();
              dbSet.Attach(entity);
              dbSet.Remove(entity);
          }
      }
  }
  </code></pre>
  
  <p>Do you think whether these methods are well implemented? Especially the <code>Add</code> method. Would it be better to implement the <code>Add</code> method as below?</p>
  
  <pre><code>public virtual void Add(T entity) {
  
      DbEntityEntry dbEntityEntry = _entitiesContext.Entry&lt;T&gt;(entity);
      if (dbEntityEntry.State == EntityState.Detached) {
  
          _entitiesContext.Set&lt;T&gt;().Attach(entity);
      }
  
      dbEntityEntry.State = EntityState.Added;
  }
  </code></pre>