How to write one read, insert, update, delete method that does the job for each database models?

1.8k Views Asked by At

I always had to write four methods (read, insert, update, delete) for each model in MVC.
I need to know if there's a better way to write less code and use some C# features like interfaces, generic types , I don't know ... etc.
And let's say I have these tables which map to their corresponding models generated by ADO.Net Entity Data Model.

enter image description here

1

There are 1 best solutions below

0
On

For simple CRUD logic, you can use generic repository pattern. Here is example:

interface IRepository<T> where T: class
{
    List<T> GetAll();
    void Add(T entity);
    void Update(T entity);
    void Remove(T entity);
}

Implementation with Entity Framework (replace DbContext with your context class):

class GenericRepository<T>: IRepository<T> where T: class
{
    public virtual List<T> GetAll()
    {
        using(var context = new DbContext())
        {
            return content.Set<T>().ToList();
        }
    }

    public virtual void Add(T entity)
    {
        using(var context = new DbContext())
        {
            context.Entry(entity).State = EntityState.Added;
            context.SaveChanges();
        }
    }

    public virtual void Update(T entity)
    {
        using(var context = new DbContext())
        {
            context.Entry(entity).State = EntityState.Modified;
            context.SaveChanges();
        }
    }

    public virtual void Remove(T entity)
    {
        using(var context = new DbContext())
        {
            context.Entry(entity).State = EntityState.Deleted;
            context.SaveChanges();
        }
    }
}

All methods are virtual so you can override them if necessary. You can use this repository directly (discouraged), or subclass it for specific type:

class UserRepository: GenericRepository<User>
{
   // other query methods here
}