Friday, July 3, 2015

Entity FrameWork With MVC5 Part 3 -Repository Framework

Earlier we saw the straight forward way of using EF with Empty controller for Read and Create Operation .we do not need to have separate repository for each entity in the application
here i will show you a more better way to do that .


we will create a generic repository that can be used with any entity


 so to do that i will create a new Folder "Repository" and create a class




public class Repository<T> where T:class



Create a global instance of context class inside it so that i can access in throughout that class




  private ProjectWBSContext pwbs = new ProjectWBSContext();


Create a DBset Property 

  protected DbSet<T> Dbset { get; set; }


Create a Method
public Repository()
        {
            Dbset = pwbs.Set<T>();
        }
Now i will include Methods to do Create and Read operations
public List<T> GetAll()
        {
        return Dbset.ToList();

        }
        public T Get(int id)
        {
            return Dbset.Find(id);
        }
        public void Add(T entity)
        {
            Dbset.Add(entity);

        }
        public void savChanges()
        {
            pwbs.SaveChanges();

        }

Next , In the Model folder i will create another class

  public class ProjectRepository:Repository<Projects>
    {
        public List<Projects> GetByName(string name)
        {
           return Dbset.Where(a => a.projectName.Contains(name)).ToList();

        }
    }
This will give me all the records matching certain conditions 

Now i will include the action methods in the controller 



public class ProjectController : Controller
    {
        ProjectRepository projRepo = new ProjectRepository();
        // GET: /Project/
        public ActionResult Index()
        {
          
           // ProjectWBSContext pwbs = new ProjectWBSContext();

            var GetAllProjects = projRepo.GetAll();
            return View(GetAllProjects);
        }

 }
Create a view if you dont have . 
Thats it. run the solution. you will find the details .



Ok . you can do that for create functionality also
just include the below method in controller



[HttpGet]
        public ActionResult Create()
        {
            //ProjectWBSContext pwbs = new ProjectWBSContext();

            return View(new Projects());
        }   
    
    }
 



        [HttpPost]
        public ActionResult Create(Projects Proj)
        {
            if(ModelState.IsValid)
            {
              
                projRepo.Add(Proj);
                projRepo.savChanges();
                return Redirect("Index");
            }

            else { return View(Proj); }

          
        }

No comments:

Post a Comment