I am just trying to use ASP.NET MVC using repository pattern. Could somebody see If I am doing something wrong here.
Model - Contains the model
public class Contact
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
}
Repository interface - Interface
public interface IContactRepository
{
void Create(Contact contact);
void Delete(int contactId);
void Save(Contact contact);
Contact Retrieve(int contactId);
IEnumerable<Contact> Select();
}
Repository class
public class ContactRepository : IContactRepository
{
private AddressBookDb addressBookdb = new AddressBookDb();
public void Create(Contact contact)
{
addressBookdb.Contacts.Add(contact);
addressBookdb.SaveChanges();
}
public void Save(Contact contact)
{
Delete(contact.Id);
Create(contact);
}
public void Delete(int contactId)
{
Contact contact = Retrieve(contactId);
if (contact != null)
{
addressBookdb.Contacts.Remove(contact);
addressBookdb.SaveChanges();
}
}
public Contact Retrieve(int contactId)
{
return addressBookdb.Contacts.FirstOrDefault<Contact>(c => c.Id == contactId);
}
public IEnumerable<Models.Contact> Select()
{
return addressBookdb.Contacts.ToList<Contact>();
}
}
Controller class
public class ContactController : Controller
{
IContactRepository contactRepository = null;
public ContactController() : this (new ContactRepository())
{
}
public ContactController(IContactRepository contactRepository)
{
this.contactRepository = contactRepository;
}
[HttpPost]
public ActionResult Edit(Contact contact)
{
if (ModelState.IsValid)
{
contactRepository.Save(contact);
return RedirectToAction("Index");
}
return View(contact);
}
}