Steps for implementing CRUD Operations using ASP.NET MVC4, Entity Framework and Generic Repository

1. Create a new ASP.NET MVC4 Web Application

NewProject

2. After clicking on OK, choose an Empty Template (I prefer empty template because I don’t want something added which I don’t know about).

EmptyTemplate

3. After clicking on OK, you would have an empty MVC4 web application project.

4. Now lets create a database to perform CRUD operations on. Create an empty database and name it Chinook (its like mini Northwind database). You can download it from here. I downloaded ChinookDatabase1.4_SqlServer.zip and after you extract the zip, you can open the .sql (AutoIncrementPKs) file with your SQL management studio and run it on Chinook database which you have already created.

Database

5. As the database is created, lets go back to Visual Studio right click on your MVC4 Web Application references and click Manage NuGet Packages.

manageNuget

6. Install GenericRepositoryUnitOfWork package. It will also install Entity Framework 5.

GenericRepositoryUntiOfWorkNuGet

7. After installing the package, lets Reverse Engineer Code First so that we can do things quickly. If you don’t know what is Reverse Engineer Code First follow below two screen shots and install it.

Extensions&Updates

EntityFrameworkPowerTools

If it is not already installed, you have to click on Online in the above screen shot and search for it and then install.

8. After you install Reverse Engineer Code First, right click on the MVC4 Web Application then go to Entity Framework under it select Reverse Engineer Code First.

 ReverseEngineerCode

9. Now select the database and click on OK and the reverse engineering process starts.

SelectDatabase

10. After reverse engineering is done, new classes will get added under Models folder.

AfterReverseEngineerCode

11. Now lets create a new folder and call it Repositories, to add our Repository classes.

NewFolder

AddRepositories

12. Add an Interface to that Repositories folder and call it IArtistRepo.cs.

IArtistRepo

13. Implement generic IRepository<Artist> as shown below.

using GenericRepositoryUnitOfWorkDemo.Models;
using Repository.Lib;
 
namespace GenericRepositoryUnitOfWorkDemo.Repositories
{
  public interface IArtistRepo : IRepository<Artist>
  {
  }
}

14. Add a new class to the Repositories folder and call it ArtistRepo.cs

ArtistRepo

15. Inherit generic Repository<Artist> and implement IArtistRepo which you created. After that add a parameterized constructor and pass your Database context to the base class as shown below.

using GenericRepositoryUnitOfWorkDemo.Models;
using Repository.Lib;
 
namespace GenericRepositoryUnitOfWorkDemo.Repositories
{
  public class ArtistRepo : Repository<Artist>, IArtistRepo
  {
    public ArtistRepo(ChinookContext context)
      : base(context)
    {
 
    }
  }
}

16.  Now that we have created IArtistRepo.cs and ArtistRepo.cs lets install Unity and Unit.MVC4 to resolve IArtistRepo to ArtistRepo when we do Dependency Injection. If you don’t know about Dependency Injection don’t worry because it is covered in the following steps.

17. Open Package Manager Console, to quickly find it Search it in you Visual studio Search as shown below.

PackageManagerConsole 

18. Paste this Install-Package Unity -Version 2.1.505.2  beside PM> and click enter.

InstallUnity

19. After installing Unity, install Unity.MVC4 by pasting Install-Package Unity.Mvc4 -Version 1.2.0 in the Package Manager Console and clicking enter.

20. Now that Unity and Unity.MVC4 NuGet packages are successfully installed for the MVC4 web application. We have to setup the Bootstrapper.cs which gets added when you install Unity.MVC4 to resolve the dependencies.

21. Add a new config file to the application and call it Unity.Config.

AddUnityConfig

22. Add the following lines to it. Where assembly name is name of your Application and namespace is namespace of the Repositories.

<?xml version="1.0"?>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
  <assembly name="GenericRepositoryUnitOfWorkDemo" />
  <namespace name="GenericRepositoryUnitOfWorkDemo.Repositories" />
  <container>
    <register type="IArtistRepo" mapTo="ArtistRepo" />
  </container>
</unity>

23. In the root web.config of the application add the following lines. Here what you are doing is creating a new section called unity and after that you are mentioning unity configuration source.

<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
  </configSections>
  <unity configSource="Unity.config" />

24. Last but not least, you have to initialize the BootStrapper in Global.asax as below.

using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
 
namespace GenericRepositoryUnitOfWorkDemo
{
  // Note: For instructions on enabling IIS6 or IIS7 classic mode,
  // visit http://go.microsoft.com/?LinkId=9394801
  public class MvcApplication : System.Web.HttpApplication
  {
    protected void Application_Start()
    {
      AreaRegistration.RegisterAllAreas();
 
      WebApiConfig.Register(GlobalConfiguration.Configuration);
      FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
      RouteConfig.RegisterRoutes(RouteTable.Routes);
 
      Bootstrapper.Initialise();
    }
  }
}

 

25. By completing the above step, Unity is now ready to inject the dependencies required but where do we need it to inject? answer is Controller. Lets create a new controller.

AddController

26. Add a controller with Empty MVC Controller template and call it ArtistController.

ControllerAdd

27. In the controller add the code as shown below. As you can see in the below code there is a private read only variable of type IArtistRepo called _repo, this _repo is used in the parameterized controller constructor. When we run this application Unity will resolve IArtistRepo to ArtistRepo. Unity is responsible to even create and instance of ArtistRepo, as you can see in the below code we never used the keyword new to create an instance of ArtistRepo.

using GenericRepositoryUnitOfWorkDemo.Repositories;
using System.Web.Mvc;
using System.Linq;
 
namespace GenericRepositoryUnitOfWorkDemo.Controllers
{
  public class ArtistController : Controller
  {
    private readonly IArtistRepo _repo;
 
    public ArtistController(IArtistRepo repo)
    {
      _repo = repo;
    }
 
    //
    // GET: /Artist/
 
    public ActionResult Index()
    {   
      // The below line of code will filter the List   
      var filteredList = _repo.GetAll(filter: a => a.Name.StartsWith("a"));  
 
      // The below line of code will sort the List   
      var sortedList = _repo.GetAll(sort: s => s.OrderBy(a => a.Name));    
 
      //If you are looking for performance then in your context     
      //you can disable LazyLoadingEnabled and ProxyCreationEnabled by setting it to false    
      //The below line of code will include the Child Entities   
      var includeList = _repo.GetAll(include: a => a.Albums);   
 
      return View(filteredList);   
      //return View(sortedList);   
      //return View(includeList);
    }
  }
}

28. Now that we have the controller ready, add a view to the Index as shown below.

AddView

AddedView

30. Run the application by hitting Ctrl+F5 and navigate to <YourLocalHost: Port>\Artist to see the result.

ArtistGrid

Last edited Jul 3, 2014 at 4:35 AM by arunendapally, version 8