Introduction
EntityFramework
, so I am referring to the same context. In this article, I’ll focus on how to implement a Repository Pattern in the same MVC application, therefore moving ahead a step towards architectural approach of developing an enterprise application.Our Roadmap
- Part1: Introduction to MVCarchitecture and Separation of Concerns.VCarchitecture and Separation of Concerns.
- Part 2: Creating MVC Application fromscratch and connecting it with database using LINQ to SQL.
- Part 3: Connecting the MVC Application with the help of EntityFramework DB-First approach.
- Part 4: Connecting the MVC Application with the help of EntityFramework Code-First approach.
- Part 5: Implementing Repository Pattern in MVC Application with EntityFramework.
- Part 6: Implementing a generic Repository Pattern and Unit Of Work pattern in MVC Application with EntityFramework.
Pre-requisites
- We have running sample application that we created in the third part of the article series.
- We have EntityFramework 4.1 package or DLL on our local file system.
- We understand how the MVC application is created.
Repository Pattern
- It centralizes the data logic or Web service access logic.
- It provides a substitution point for the unit tests.
- It provides a flexible architecture that can be adapted as the overall design of the application evolves.
Creating Repository
IUserRepository
, this interface we derive from IDisposable
type of interface.using System; using System.Collections.Generic;
namespace LearningMVC.Repository
{
public interface IUserRepository:IDisposable
{
IEnumerable GetUsers();
User GetUserByID(int userId);
void InsertUser(User user);
void DeleteUser(int userId);
void UpdateUser(User user);
void Save();
}
}
UserRepository
. This UserRepository
class will implement all the methods of that interface, but with the help of Entity Framework. Now here comes the use of our DBContext
class MVCEntities
, we already have this class in our existing solution, so we don’t have to touch this class, simply, write our business logic in the interface methods implemented in UserRepository
class:using System; using System.Collections.Generic; using System.Data; using System.Linq;
namespace LearningMVC.Repository
{
public class UserRepository:IUserRepository
{
private MVCEntities context;
public UserRepository(MVCEntities context)
{
this.context = context;
}
public IEnumerable GetUsers()
{
return context.Users.ToList();
}
public User GetUserByID(int userId)
{
return context.Users.Find(userId);
}
public void InsertUser(User user)
{
context.Users.Add(user);
}
public void DeleteUser(int userId)
{
User user = context.Users.Find(userId);
context.Users.Remove(user);
}
public void UpdateUser(User user)
{
context.Entry(user).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);
}
}
}
Interface
Class
IUserRepository
reference, and in the constructor initialize the object withUserRepository
class, passing MVCEntities
to the constructor as parameter we defined in UserRepository
class:#region Private member variables... private IUserRepository userRepository; #endregion
#region Public Constructor…
/// <summary>
/// Public Controller to initialize User Repository
/// </summary>
public MyController()
{
this.userRepository = new UserRepository(new MVCEntities());
}
#endregion
userRepository
object, and call methods defined in repository
class.var userList = from user in userRepository.GetUsers() select user; var users = new List(); if (userList.Any()) { foreach (var user in userList) { users.Add(new LearningMVC.Models.UserList() { UserId = user.UserId, Address = user.Address, Company = user.Company, FirstName = user.FirstName, LastName = user.LastName, Designation = user.Designation, EMail = user.EMail, PhoneNo = user.PhoneNo }); } }
Details
Create
Edit
Delete
Conclusion
- You want to maximize the amount of code that can be tested with automation and to isolate the data layer to support unit testing.
- You access the data source from many locations and want to apply centrally managed, consistent access rules and logic.
- You want to implement and centralize a caching strategy for the data source.
- You want to improve the code’s maintainability and readability by separating business logic from data or service access logic.
- You want to use business entities that are strongly typed so that you can identify problems at compile time instead of at run time.
- You want to associate a behavior with the related data. For example, you want to calculate fields or enforce complex relationships or business rules between the data elements within an entity.
- You want to apply a domain model to simplify complex business logic.
Read more:
- C# and ASP.NET Questions (All in one)
- MVC Interview Questions
- C# and ASP.NET Interview Questions and Answers
- Web Services and Windows Services Interview Questions
Other Series
My other series of articles:
For more informative articles visit my Blog.
For more technical articles you can reach out to CodeTeddy.
4 comments