Saturday, January 5, 2013

EF Repository Pattern

IPerformerRepository.cs

namespace SCNData
{
    public interface IPerformerRepository : IDisposable
    {
        IEnumerable<Performer> GetPerformers();
        Performer GetPerformerByID(int performerId);
        void InsertPerformer(Performer performer);
        void DeletePerformer(int performerID);
        void UpdatePerformer(Performer performer);
        void Save();
    }
}


PerformerRepository.cs

namespace SCNData
{
    public class PerformerRepository : IPerformerRepository, IDisposable
    {
        private NhacContext context;
        public PerformerRepository(NhacContext context)
        {
            this.context = context;
        }
        public IEnumerable<Performer> GetPerformers()
        {
            return context.Performers.ToList();
        }
        public Performer GetPerformerByID(int id)
        {
            return context.Performers.Find(id);
        }
        public void InsertPerformer(Performer performer)
        {
            context.Performers.Add(performer);
        }
        public void DeletePerformer(int performerId)
        {
            Performer performer = context.Performers.Find(performerId);
            context.Performers.Remove(performer);
        }
        public void UpdatePerformer(Performer performer)
        {
            context.Entry(performer).State = EntityState.Modified;
        }
        public void Save()
        {
            context.SaveChanges();
        }
        private bool disposed = false;
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    context.Dispose();
                }
            }
            this.disposed = true;
        }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}
 
 

No comments: