Most efficiently handling Create, Update, Delete with Entity Framework Code First

28,615

For add:

public bool Add<E>(E entity) where E : class
        {
            DataContext.Entry(entity).State = System.Data.EntityState.Added;
            Save();
        }

For update:

 public bool Update<E>(E entity) where E : class
        {
            DataContext.Entry(entity).State = System.Data.EntityState.Modified;
            Save();
        }

For delete:

 public bool Delete<E>(E entity) where E : class
        {
            DataContext.Entry(entity).State = System.Data.EntityState.Deleted;
            Save();
        }

And a private Save() method that returns true or false so you can fallback easy in the controller depending on the result

private bool Save()
        {
            return DataContext.SaveChanges() > 0;                
        }

This is only a portion of my generic repository. It works great in enterprise applications.

UPDATE:

Detach only affects the specific object passed to the method. If the object being detached has related objects in the object context, those objects are not detached.

EF will automatically attach detached objects in the graph when setting the state of an entity or when SaveChanges() is called.

I really don't know why you need to detach objects from the context. You can also use AsNoTracking() to load entities from the database without attaching them to the context in the first place.

Share:
28,615
tugberk
Author by

tugberk

Senior Software Engineer and Tech Lead, with a growth mindset belief and 10+ years of practical software engineering experience including technical leadership and distributed systems. I have a passion to create impactful software products, and I care about usability, reliability, observability and scalability of the software systems that I work on, as much as caring about day-to-day effectiveness, productivity and happiness of the team that I work with. I occasionally speak at international conferences (tugberkugurlu.com/speaking), and write technical posts on my blog (tugberkugurlu.com). I currently work at Facebook as a Software Engineer. I used to work at Deliveroo as a Staff Software Engineer in the Consumer division, working on distributed backend systems which have high throughput, low latency and high availability needs. Before that, I used to work at Redgate as a Technical Lead for 4 years, where I led and line-managed a team of 5 Software Engineers. I was responsible for all aspects of the products delivered by the team from technical architecture to product direction. I was also a Microsoft MVP for 7 years between 2012-2019 on Microsoft development technologies.

Updated on September 21, 2020

Comments

  • tugberk
    tugberk over 3 years

    Note: I am using Entity Framework version 5

    Inside my generic repository, I have Add, Edit and Delete methods as below:

    public class EntityRepository<T> : IEntityRepository<T>
        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<T>(entity);
            if (dbEntityEntry.State != EntityState.Detached) {
    
                dbEntityEntry.State = EntityState.Added;
            }
            else {
    
                _entitiesContext.Set<T>().Add(entity);
            }
        }
    
        public virtual void Edit(T entity) {
    
            DbEntityEntry dbEntityEntry = _entitiesContext.Entry<T>(entity);
            if (dbEntityEntry.State == EntityState.Detached) {
    
                _entitiesContext.Set<T>().Attach(entity);
            }
    
            dbEntityEntry.State = EntityState.Modified;
        }
    
        public virtual void Delete(T entity) {
    
            DbEntityEntry dbEntityEntry = _entitiesContext.Entry<T>(entity);
            if (dbEntityEntry.State != EntityState.Detached) {
    
                dbEntityEntry.State = EntityState.Deleted;
            }
            else {
    
                DbSet dbSet = _entitiesContext.Set<T>();
                dbSet.Attach(entity);
                dbSet.Remove(entity);
            }
        }
    }
    

    Do you think whether these methods are well implemented? Especially the Add method. Would it be better to implement the Add method as below?

    public virtual void Add(T entity) {
    
        DbEntityEntry dbEntityEntry = _entitiesContext.Entry<T>(entity);
        if (dbEntityEntry.State == EntityState.Detached) {
    
            _entitiesContext.Set<T>().Attach(entity);
        }
    
        dbEntityEntry.State = EntityState.Added;
    }