Nick Kewney

Software Architect & Product Builder

Design pattern for ASP.NET MVC 3 application using repository pattern

Below is an example of how I typically implement the repository pattern in an ASP.NET MVC 3 project when using Entity Framework.

Model (Address.cs)

  [Bind(Include = "Id,Address")]  [MetadataType(typeof(Address_Validation))]  public partial class Address {}  public class Address_Validation
{ //validation here }

Repository Interface (IAddressRepository.cs)

public interface IAddressRepository  {
void Delete(Address u);
void Save();
void Add(Address b);
Address GetAddressById(int intAddressId);
}

Repository class (AddressRepository.cs)

public class AddressRepository : IAddressRepository 
{
private myEntities db = new myEntities();
public Address GetAddressById(int intAddressId)
{
return db.Addresses.FirstOrDefault(d => ((d.Address_ID == intAddressId)))
}
public void Delete(Address u)
{
db.Addresses.DeleteObject(u);
}
public void Save()
{
db.SaveChanges();
}
public void Add(Address b)
{
db.AddToAddresses(b);
db.SaveChanges();
}
}

Controller (AddressController.cs)

  public class AddressController : Controller
{ private IAddressRepository _addressRepository { get; set; } protected override void Initialize(RequestContext requestContext) {

if (_addressRepository == null)
{
_addressRepository = new AddressRepository();
}
base.Initialize(requestContext);
}
[AcceptVerbs(HttpVerbs.Post)] // Example..
public ActionResult _AddressInsert(AddressPartial objItem)
{
try
{ var objAddress = new Address
{
AddressTypeID = objItem.AddressTypeID,
...
} _addressRepository.Add(objAddress); _addressRepository.Save(); } }

Moving IContactRepository to a IRepository<T> interface would avoid code repetition and allow you to share the interface between all your repositories.

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on whatsapp
WhatsApp

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.