Home > DeveloperSection > Forums > How to use generic repository pattern in mvc code first.
Ankit Singh

Total Post:341

Points:2389
Posted on    October-26-2015 10:19 PM

 .NET Mvc  Entity Framework 
Ratings:


 1 Reply(s)
 412  View(s)
Rate this:
Can anyone please help me how to solve this problem.


aditya kumar Patel

Total Post:250

Points:1782
Posted on    October-26-2015 10:55 PM



We have first created core class library project and I mentioned database model structure in master.cs.

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.ComponentModel.DataAnnotations.Schema;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace Core

{     public class UserMaster

    {

        [Key]

        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]

        public int UserId { get; set; }

        public string LoginName { get; set; }

        public string password { get; set; }

        public string UserName { get; set; }

        public string ReturnUrl { get; set;

    }

    public class CustomerProduct

    {

        [Key]

        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]

        public int Id { get; set; }

        public int ProductId { get; set; }

        public decimal Price { get; set; }

        public decimal Quantity { get; set; }

        public decimal TotalAmount { get; set; }

        public virtual ProductMaster ProductMaster { get; set; }

    }

    public class ProductMaster

    {

        public ProductMaster()

        {

            CustomerProducts = new HashSet<CustomerProduct>();

        }

        [Key]

        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]

        public int ProductId { get; set; }

        public string ProductName { get; set; }

        public decimal Price { get; set; }

        public int CategoryId { get; set; }

        public virtual CategotyMaster CategotyMaster { get; set; }

        public virtual ICollection<CustomerProduct> CustomerProducts { get; set; }

    }

    public class CategotyMaster

    {

        public CategotyMaster()

        {

            ProductMasters = new HashSet<ProductMaster>();

        }

        [Key]

        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]

        public int CategoryId { get; set; }

        public string CategoryName { get; set; }

        public virtual ICollection<ProductMaster> ProductMasters { get; set; }

    }

}



Second  we have created data class library project and mention Repository pattern and

codefirst entity framework .

Create IRepository interface

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace Data

{

    public interface IRepository<T> where T : class

    {

        IQueryable<T> GetAll();

        void Add(T obj);

        void Delete(object Id);

        void Update(T obj);

        T GetById(object id);      

    }

}

Next create a new repository class which is implement IRepository interface .

using System;

using System.Collections.Generic;

using System.Data.Entity;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace Data

{

    public class Repository<T> :IRepository<T> where T : class

    {

         private DataContext context = null;

         private DbSet<T> table = null;

         public Repository()

        {             this.context = new DataContext();

            this.context.Configuration.ProxyCreationEnabled = false;

            table = context.Set<T>();

        }

         public Repository(DataContext context)

        {

            this.context = context;

            this.context.Configuration.ProxyCreationEnabled = false;

            table = context.Set<T>();

        }

         public IQueryable<T> GetAll()

         {

             return table;

         }

         public void Add(T obj)

         {

             table.Add(obj);

             context.SaveChanges();

         }

         public void Delete(object Id)

         {

             T existing = table.Find(Id);

             table.Remove(existing);

             context.SaveChanges();

         }

         public void Update(T obj)

         {

             table.Attach(obj);

             context.Entry(obj).State = EntityState.Modified;

         }

         public T GetById(object id)

         {

             return table.Find(id);       

         }

    }

}

Next create a new DataContext class which is implement entity framework.

using System;

using System.Collections.Generic;

using System.Data.Entity;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Data.Entity.ModelConfiguration;

using System.Reflection;

using System.Configuration;

using Core;

namespace Data

{

   public class DataContext : DbContext

    {

        public DataContext()

        : base(ConfigurationManager.ConnectionStrings["con"].ConnectionString)

        {           

        Database.SetInitializer<DataContext>(new CreateDatabaseIfNotExists<DataContext>());

        this.Configuration.LazyLoadingEnabled = false;

        }     

        public DbSet<ProductMaster> ProductMasters { get; set; }

        public DbSet<CustomerProduct> CustomerProducts { get; set; }

        public DbSet<CategotyMaster> CategotyMasters { get; set; }

        public DbSet<UserMaster> UserMasters { get; set; }

    }

}

Next create a new DMLRempsitory class which is set generic IRepository property.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using Data;

using Core;

using System.Data.Entity;

using System.Configuration;

namespace Data

{

    public class DMLRempsitory

    {

       public IRepository<CustomerProduct> CustomerProduct {

            get

            {                return new Repository<CustomerProduct>();

            } 

        }

        public IRepository<ProductMaster> ProductMaster {

            get

            {

                return new Repository<ProductMaster>();

            }            }

        public IRepository<CategotyMaster> CategotyMaster

        {

            get

            {                 return  new Repository<CategotyMaster>();

            }   

        }

        public IRepository<UserMaster> UserMaster

        {

            get

            {

                return new Repository<UserMaster>();

            }

        }

    }

}



Next create a new BaseController class which is inherits Controller where we create a property of DMLRempsitory class which is get all property.

using Data;

using System;

using System.Collections.Generic;

using System.Configuration;

using System.Data.Entity;

using System.Linq;

using System.Web;

using System.Web.Mvc;

namespace ReposityPattern.Controllers

{

    public class BaseController : Controller

    {

        protected DMLRempsitory Uow { get; set; }

        public BaseController()

        {

            Uow = new DMLRempsitory();

        }

    }

}

Next create a new HomeController class which is inherits BaseController help to access all property of DMLRempsitory class.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using Data;

using Core;

using ReposityPattern.Models;

using System.Data.Entity;

namespace ReposityPattern.Controllers

{

    public class HomeController : BaseController

    {

        public ActionResult Index()

        {

            return View();

        }

        public JsonResult GetCategoty()

        {

            var Result = Uow.CategotyMaster.GetAll();

            return Json(Result, JsonRequestBehavior.AllowGet);

        }

        [HttpPost]

        public ActionResult Delete(CustomerProduct obj)

        {

            Uow.CustomerProduct.Delete(obj.Id);

            SaveChanges();

            return new EmptyResult();

        }

        public ActionResult GetProduct(int categoryId = 0)

        {

            var result = (from a in Uow.ProductMaster.GetAll().ToList()

                          where a.CategoryId == categoryId

                          select new

                          {

                              a.ProductId,

                              a.ProductName

                          });

            return Json(result, JsonRequestBehavior.AllowGet);

        }

        public ActionResult GetProductDetails(int ProductId = 0)

        {

            var result = (from a in Uow.ProductMaster.GetAll().ToList()

                          join b in Uow.CategotyMaster.GetAll().ToList() on a.CategoryId equals b.CategoryId

                          where a.ProductId == ProductId

                          select new

                          {

                              a.ProductId,

                              a.ProductName,

                              a.Price,

                              b.CategoryId,

                              b.CategoryName

                          });

            return Json(result, JsonRequestBehavior.AllowGet);

        }

        public void Insert(IList<CustomerProduct> obj)

        {

            foreach (CustomerProduct o in obj)

            {

                Uow.CustomerProduct.Add(o)

            }

        }

    }

}


Don't want to miss updates? Please click the below button!

Follow MindStick