public void Add(KhuyenMaiViewModel model) { var khuyenMai = new KHUYENMAI() { TenKhuyenMai = model.TenKhuyenMai, GiaTriKhuyenMai = model.GiaTriKhuyenMai, NgayBatDau = model.NgayBatDau, NgayKetThuc = model.NgayKetThuc, }; context.KHUYENMAIs.Add(khuyenMai); context.SaveChanges(); if (model.SanPhams?.Count > 0) { //foreach (var item in model.SanPhams) //{ // var sanPham = context.SANPHAMs.FirstOrDefault(t => t.Id_SanPham == item && t.TrangThai != false); // if (sanPham == null) continue; // sanPham.Id_KhuyenMai = khuyenMai.Id_KhuyenMai; //} UpdateKhuyenMaiForSanPham(model.SanPhams, khuyenMai.Id_KhuyenMai, true); } context.SaveChanges(); }
public ActionResult Edit(KhuyenMaiViewModel model) { try { // TODO: Add update logic here var result = KMService.Update(model); if (!result) { return(HttpNotFound()); } return(RedirectToAction("Index")); } catch { return(View()); } }
public ActionResult Create(KhuyenMaiViewModel collection) { try { // TODO: Add insert logic here if (ModelState.IsValid) { KMService.Add(collection); return(RedirectToAction("Index")); } return(View(collection)); } catch { return(View()); } }
public bool Update(KhuyenMaiViewModel khuyenMai) { KHUYENMAI khuyenMaiExist = context.KHUYENMAIs .Include(t => t.SANPHAMs) .FirstOrDefault(t => t.Id_KhuyenMai == khuyenMai.Id_KhuyenMai); if (khuyenMaiExist == null) { return(false); } khuyenMaiExist.TenKhuyenMai = khuyenMai.TenKhuyenMai; khuyenMaiExist.NgayBatDau = khuyenMai.NgayBatDau; khuyenMaiExist.NgayKetThuc = khuyenMai.NgayKetThuc; khuyenMaiExist.GiaTriKhuyenMai = khuyenMai.GiaTriKhuyenMai; //update san pham apply var existSanPhamIds = khuyenMaiExist.SANPHAMs.Where(t => t.TrangThai != false) .Select(t => t.Id_SanPham).ToList(); // New var newIds = khuyenMai.SanPhams.Except(existSanPhamIds).ToList(); if (newIds.Count > 0) { UpdateKhuyenMaiForSanPham(newIds, khuyenMai.Id_KhuyenMai, true); } // remove old var removeIds = existSanPhamIds.Except(khuyenMai.SanPhams).ToList(); if (removeIds.Count > 0) { UpdateKhuyenMaiForSanPham(removeIds, khuyenMai.Id_KhuyenMai, false); } context.SaveChanges(); return(true); }