Best Repository Pattern for ASP.NET MVC

后端 未结 4 379
野的像风
野的像风 2020-12-07 06:54

I recently learned ASP.NET MVC (I love it). I\'m working with a company that uses dependency injection to load a Repository instance in each request, and I\'m familiar with

4条回答
  •  自闭症患者
    2020-12-07 07:32

    Here we go for Best Repository Pattern in Asp.Net MVC:

    The Repository pattern adds a separation layer between the data and domain layers of an application. It also makes the data access parts of an application better testable.

    Database Factory (IDatabaseFactory.cs):

    public interface IDatabaseFactory : IDisposable
    {
        Database_DBEntities Get();
    }
    

    Database Factory Implementations (DatabaseFactory.cs):

    public class DatabaseFactory : Disposable, IDatabaseFactory
    {
        private Database_DBEntities dataContext;
        public Database_DBEntities Get()
        {
            return dataContext ?? (dataContext = new Database_DBEntities());
        }
    
        protected override void DisposeCore()
        {
            if (dataContext != null)
                dataContext.Dispose();
        }
    }
    

    Base Interface (IRepository.cs):

    public interface IRepository where T : class
    {
        void Add(T entity);
        void Update(T entity);
        void Detach(T entity);
        void Delete(T entity);
        T GetById(long Id);
        T GetById(string Id);
        T Get(Expression> where);
        IEnumerable GetAll();
        IEnumerable GetMany(Expression> where);
        void Commit();
    }
    

    Abstract Class (Repository.cs):

    public abstract class Repository : IRepository where T : class
    {
        private Database_DBEntities dataContext;
        private readonly IDbSet dbset;
        protected Repository(IDatabaseFactory databaseFactory)
        {
            DatabaseFactory = databaseFactory;
            dbset = DataContext.Set();
        }
    
        /// 
        /// Property for the databasefactory instance
        /// 
        protected IDatabaseFactory DatabaseFactory
        {
            get;
            private set;
        }
    
        /// 
        /// Property for the datacontext instance
        /// 
        protected Database_DBEntities DataContext
        {
            get { return dataContext ?? (dataContext = DatabaseFactory.Get()); }
        }
    
        /// 
        /// For adding entity
        /// 
        /// 
        public virtual void Add(T entity)
        {
            try
            {
                dbset.Add(entity);
                //  dbset.Attach(entity);
                dataContext.Entry(entity).State = EntityState.Added;
                int iresult = dataContext.SaveChanges();
            }
            catch (UpdateException ex)
            {
            }
            catch (DbUpdateException ex) //DbContext
            {
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    
        /// 
        /// For updating entity
        /// 
        /// 
        public virtual void Update(T entity)
        {
            try
            {
                // dbset.Attach(entity);
                dbset.Add(entity);
                dataContext.Entry(entity).State = EntityState.Modified;
                int iresult = dataContext.SaveChanges();
            }
            catch (UpdateException ex)
            {
                throw new ApplicationException(Database_ResourceFile.DuplicateMessage, ex);
            }
            catch (DbUpdateException ex) //DbContext
            {
                throw new ApplicationException(Database_ResourceFile.DuplicateMessage, ex);
            }
            catch (Exception ex) {
                throw ex;
            }
        }
    
        /// 
        /// for deleting entity with class 
        /// 
        /// 
        public virtual void Delete(T entity)
        {
            dbset.Remove(entity);
            int iresult = dataContext.SaveChanges();
        }
    
        //To commit save changes
        public void Commit()
        {
            //still needs modification accordingly
            DataContext.SaveChanges();
        }
    
        /// 
        /// Fetches values as per the int64 id value
        /// 
        /// 
        /// 
        public virtual T GetById(long id)
        {
            return dbset.Find(id);
        }
    
        /// 
        /// Fetches values as per the string id input
        /// 
        /// 
        /// 
        public virtual T GetById(string id)
        {
            return dbset.Find(id);
        }
    
        /// 
        /// fetches all the records 
        /// 
        /// 
        public virtual IEnumerable GetAll()
        {
            return dbset.AsNoTracking().ToList();
        }
    
        /// 
        /// Fetches records as per the predicate condition
        /// 
        /// 
        /// 
        public virtual IEnumerable GetMany(Expression> where)
        {
            return dbset.Where(where).ToList();
        }
    
        /// 
        /// 
        /// 
        /// 
        public void Detach(T entity)
        {
            dataContext.Entry(entity).State = EntityState.Detached;
        }
    
        /// 
        /// fetches single records as per the predicate condition
        /// 
        /// 
        /// 
        public T Get(Expression> where)
        {
            return dbset.Where(where).FirstOrDefault();
        }
    }
    

    How to access this repository pattern in controller:

    1. You have User Model :

    public partial class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    

    2. Now you have to create Repository Class of your UserModel

    public class UserRepository : Repository, IUserRepository
    {
        private Database_DBEntities dataContext;
    
        protected IDatabaseFactory DatabaseFactory
        {
            get;
            private set;
        }
    
        public UserRepository(IDatabaseFactory databaseFactory)
            : base(databaseFactory)
        {
            DatabaseFactory = databaseFactory;
        }
    
        protected Database_DBEntities DataContext
        {
            get { return dataContext ?? (dataContext = DatabaseFactory.Get()); }
        }
    
        public interface IUserRepository : IRepository
        { 
        }
    }
    

    3. Now you have to create UserService Interface (IUserService.cs) with all CRUD Methods:

    public interface IUserService
    {
        #region User Details 
        List GetAllUsers();
        int SaveUserDetails(User Usermodel);
        int UpdateUserDetails(User Usermodel);
        int DeleteUserDetails(int Id);
        #endregion
    }
    

    4. Now you have to create UserService Interface (UserService.cs) with all CRUD Methods:

    public class UserService : IUserService
    {
        IUserRepository _userRepository;
        public UserService() { }
        public UserService(IUserRepository userRepository)
        {
            this._userRepository = userRepository;
        }
    
        public List GetAllUsers()
        {
            try
            {
                IEnumerable liUser = _userRepository.GetAll();
                return liUser.ToList();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    
        /// 
        /// Saves the User details.
        /// 
        /// The deptmodel.
        /// 
        public int SaveUserDetails(User Usermodel)
        {
            try
            {
                if (Usermodel != null)
                {
                    _userRepository.Add(Usermodel);
                    return 1;
                }
                else
                    return 0;
            }
            catch
            {
                throw;
            }
       }
    
       /// 
       /// Updates the User details.
       /// 
       /// The deptmodel.
       /// 
       public int UpdateUserDetails(User Usermodel)
       {
           try
           {
               if (Usermodel != null)
               {
                   _userRepository.Update(Usermodel);
                   return 1;
               }
               else
                   return 0;
           }
           catch
           {
               throw;
           }
       }
    
       /// 
       /// Deletes the User details.
       /// 
       /// The code identifier.
       /// 
       public int DeleteUserDetails(int Id)
       {
           try
           {
               User Usermodel = _userRepository.GetById(Id);
               if (Usermodel != null)
               {
                   _userRepository.Delete(Usermodel);
                   return 1;
               }
               else
                   return 0;
           }
           catch
           {
               throw;
           }
       }
    }
    

    5. Now you All set for your Repository Pattern and you can access all data in User Controller:

    //Here is the User Controller 
    public class UserProfileController : Controller
    {
        IUserService _userservice;
        public CustomerProfileController(IUserService userservice)
        {
            this._userservice = userservice;
        }
    
        [HttpPost]
        public ActionResult GetAllUsers(int id)
        {
            User objUser=new User();
    
            objUser = _userservice.GetAllUsers().Where(x => x.Id == id).FirstOrDefault();
        }
    }
    

提交回复
热议问题