Tutorial ini adalah sambungan dari Hands On Labs ASP.NET MVC Part1
Membuat Product Repository
Pada small application tidak menjadi masalah jika kita mengakses LINQ to SQL DataContex class langsung dari Controller, namun jika aplikasinya bertambah kompleks maka akan sulit untuk di maintain dan melakukan tes terhadap kode-kode tersebut, akan terjadi duplikasi banyak code pada aplikasi kita (berlawanan dengan prinsip MVC yaitu DRY = Don’t Repeat Yourself).
Teknik yang dapat digunakan untuk membuat aplikasi kita lebih mudah di maintain adalah dengan menggunakan “repository pattern” yaitu membuat repository class yang mengenkapsulasi query dan persistance logic sehingga aplikasi kita menjadi lebih clean.
1. Tambahkan class baru kedalam folder “Model”, beri nama “ProductRepository.cs”. kemudian tulis kode berikut:
1: namespace ComputerStore.Models {
2: public class ProductRepository {
3: StoreDataContext db = new StoreDataContext();
4:
5: //menampilkan semua product, digunakan pada View Index
6: public IQueryable<Product> ShowAllProduct() {
7: var query = from p in db.Products
8: orderby p.Id
9: select p;
10: return query;
11: }
12:
13: //menambah product baru, digunakan pada View Create
14: public void CreateProduct(Product productToCreate) {
15: db.Products.InsertOnSubmit(productToCreate);
16: }
17:
18: //mengambil product berdasarkan id tertentu
19: public Product ShowProduct(int id) {
20: Product prod = db.Products.Where(p => p.Id == id).Single<Product>();
21: return prod;
22: }
23:
24: //mengedit product
25: public void EditProduct(Product productToEdit) {
26: Product prod = db.Products.Where(p => p.Id == productToEdit.Id).Single<Product>();
27: prod.Name = productToEdit.Name;
28: prod.Price = productToEdit.Price;
29: prod.Qty = productToEdit.Qty;
30: prod.BuyDate = productToEdit.BuyDate;
31: }
32:
33: //menghapus product
34: public void DeleteProduct(int id) {
35: Product prod = db.Products.Where(p => p.Id == id).Single<Product>();
36: db.Products.DeleteOnSubmit(prod);
37: }
38:
39: public void Save() {
40: db.SubmitChanges();
41: }
42: }
43: }
2. StoreDataContext adalah class yang digenerate oleh tools LINQ to SQL Classes, yang berisi object model dari table Products. Untuk mngakses data maka kita menggunakan standar query expression dari LINQ. Query expression tersebut akan diterjemahkan oleh LINQ to SQL menjadi T-SQL sintaks untuk dieksekusi oleh database.
Membuat Controller
Sesudah membuat Model, kemudian langkah selanjutnya adalam membuat Controller. Pada aplikasi MVC, Controller Berisi Control-flow logic. Controller berinteraksi dengan Model dan View untuk mengontrol jalannya aplikasi.
1. Pada solution explorer klik kanan folder “Controller”, pilih “Add” – “Controller”, beri nama “Home Controller”, kemudian check pada pilihan “Add action method for create, update, and details scenario” untuk menambahkan secara otomatis ActionMethod yang akan kita buat untuk menghandle proses CRUD (create, read, update, dan delete) .
2. Kemudian tambahkan kode berikut pada Controller:
1: namespace ComputerStore.Controllers
2: {
3: public class HomeController : Controller
4: {
5: private ProductRepository productRepo = new ProductRepository();
6: //
7: // GET: /Home/
8:
9: public ActionResult Index() {
10: return View(productRepo.ShowAllProduct());
11: }
12:
13: public ActionResult About() {
14: return View();
15: }
16:
17:
18: //
19: // GET: /Home/Details/5
20:
21: public ActionResult Details(int id)
22: {
23: return View();
24: }
25:
26: //
27: // GET: /Home/Create
28:
29: public ActionResult Create()
30: {
31: return View();
32: }
33:
34: //
35: // POST: /Home/Create
36:
37: [AcceptVerbs(HttpVerbs.Post)]
38: public ActionResult Create([Bind(Exclude="Id")] Product productToCeate)
39: {
40: if (ModelState.IsValid) {
41: try {
42: // TODO: Add insert logic here
43: productRepo.CreateProduct(productToCeate);
44: productRepo.Save();
45: return RedirectToAction("Index");
46: }
47: catch {}
48: }
49: return View(productToCeate);
50: }
51:
52: //
53: // GET: /Home/Edit/5
54:
55: public ActionResult Edit(int id)
56: {
57: return View(productRepo.ShowProduct(id));
58: }
59:
60: //
61: // POST: /Home/Edit/5
62:
63: [AcceptVerbs(HttpVerbs.Post)]
64: public ActionResult Edit(Product productToEdit)
65: {
66: if (ModelState.IsValid) {
67: try {
68: // TODO: Add update logic here
69: productRepo.EditProduct(productToEdit);
70: productRepo.Save();
71: return RedirectToAction("Index");
72: }
73: catch {}
74: }
75: return View(productToEdit);
76: }
77:
78: public ActionResult Delete(int id) {
79: Product prod = productRepo.ShowProduct(id);
80: return View(prod);
81: }
82:
83: [AcceptVerbs(HttpVerbs.Post)]
84: public ActionResult Delete(int id,string confirmButton) {
85: try {
86: productRepo.DeleteProduct(id);
87: productRepo.Save();
88: }
89: catch {}
90: return View("Deleted");
91: }
92:
93: }
94: }
Kemuadian langkah selanjutnya adalah pembuatan “View” yang akan dijelaskan di bagian selanjutnya ..
2 thoughts on “ASP.NET MVC Hands On Labs (Part2 – Membuat Model dan Controller)”