Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}
like image 638
tugberk Avatar asked Oct 05 '12 08:10

tugberk


People also ask

What is DbSet in Entity Framework?

A DbSet represents the collection of all entities in the context, or that can be queried from the database, of a given type. DbSet objects are created from a DbContext using the DbContext. Set method.

What is DbContext in Entity Framework?

A DbContext instance represents a combination of the Unit Of Work and Repository patterns such that it can be used to query from a database and group together changes that will then be written back to the store as a unit. DbContext is conceptually similar to ObjectContext.

What are the approaches in Entity Framework?

There are three approaches to model your entities in Entity Framework: Code First, Model First, and Database First. This article discusses all these three approaches and their pros and cons.


1 Answers

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.

like image 84
Matija Grcic Avatar answered Sep 30 '22 15:09

Matija Grcic