mercredi 13 mai 2015

MVC Design query on Controller/Models

New to MVC, I am currently working on a small application to practice. For database interaction, I am making use of Entity framework for this project.

Questions -

  1. Should the methods that directly use database context object be part of Controller classes or Models?
  2. ContactManagerContext.cs (which I am considering as a DAL layer?) Is my assumption correct?
  3. Where should the ContactManager class be placed? Model or DAL? It is currently part of the Model class.
  4. will add more questions

This is how I have structured the classes - Models and Controllers.

Please review and comment on if the code is structured correctly or not and how it can be improved.

Model class (Contact.cs):

using Contact_Manager.DAL;

namespace Contact_Manager.Models
{

public class Contact
{
    [Key]
    public int ContactId { get; set; }
    [Required, MaxLength(100)]
    public string FirstName { get; set; }
    [Required, MaxLength(100)]
    public string LastName { get; set; }
    public string EMail { get; set; }
    public string Phone { get; set; }
    public string BusinessName { get; set; }
}

public class ContactManager
{
    ContactContext db = new ContactContext();

    public IEnumerable<Contact> ContactList(int? selectedContact)
    {

        IQueryable<Contact> contacts = db.Contacts;

        return contacts.ToList();

    }

    }
}

ContactManagerContext.cs (DAL)
------------------------------

using System.Data.Entity;
using System.Linq;
using Contact_Manager.Models;


namespace Contact_Manager.DAL
{
    public class ContactContext : DbContext
    {

        public ContactContext()
            : base("ContactMgrDBContext")
        {
            Database.SetInitializer<ContactContext>(new      DropCreateDatabaseIfModelChanges<ContactContext>());
        }

        public DbSet<Contact> Contacts { get; set; }

    }

}

ContactController.cs (Controller class):

using System.Web.Mvc;
using System.Linq;
using Contact_Manager.Models;

namespace Contact_Manager.Controllers
{
    public class ContactController : Controller
    {

        //
        // GET: /Contact/

        public JsonResult ContactList()
        {

            ContactManager cMgr = new ContactManager();

            IEnumerable<Contact> contactList = cMgr.ContactList(0);

            //var contactsJson = JsonConvert.SerializeObject(contacts.ToList());

            return Json(contactList, JsonRequestBehavior.AllowGet);

        }

        public ActionResult Index()
        {
            return View();
        }



    }
}

Aucun commentaire:

Enregistrer un commentaire