How can I implement CRUD operations in a base class for an entity framework app?
        Posted  
        
            by hminaya
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by hminaya
        
        
        
        Published on 2010-05-18T21:40:50Z
        Indexed on 
            2010/05/18
            21:50 UTC
        
        
        Read the original article
        Hit count: 333
        
I'm working a simple EF/MVC app and I'm trying to implement some Repositories to handle my entities. I've set up a BaseObject Class and a IBaseRepository Interface to handle the most basic operations so I don't have to repeat myself each time:
public abstract class BaseObject<T>
    {
        public XA.Model.Entities.XAEntities db;
        public BaseObject()
        {
            db = new Entities.XAEntities();
        }
        public BaseObject(Entities.XAEntities cont)
        {
            db = cont;
        }
        public void Delete(T entity)
        {
            db.DeleteObject(entity);
            db.SaveChanges();
        }
        public void Update(T entity)
        {
            db.AcceptAllChanges();
            db.SaveChanges();
        }
   }
    public interface IBaseRepository<T>
    {
        void Add(T entity);
        T GetById(int id);
        IQueryable<T> GetAll();
    }
But then I find myself having to implement 3 basic methods in every Repository ( Add, GetById & GetAll):
public class AgencyRepository : Framework.BaseObject<Agency>, Framework.IBaseRepository<Agency>
    {
        public void Add(Agency entity)
        {
            db.Companies.AddObject(entity);
            db.SaveChanges();
        }
        public Agency GetById(int id)
        {
            return db.Companies.OfType<Agency>().FirstOrDefault(x => x.Id == id);
        }
        public IQueryable<Agency> GetAll()
        {
            var agn = from a in db.Companies.OfType<Agency>()
                      select a;
            return agn;
        }
    }
How can I get these into my BaseObject Class so I won't run in conflict with DRY.
© Stack Overflow or respective owner