public bool UpdateProduct(Product product, int[] images) { bool result = false; using (AnanEntities db = new AnanEntities()) { Product old = (from p in db.Product where p.ID == product.ID select p).FirstOrDefault<Product>(); List<Image> imgs = null; List<int> newImg = new List<int>(); if (old != null) { product.Created = old.Created; base.UpdateProperties(old, product); db.SaveChanges(); imgs=(from i in db.Image where i.ProductID==product.ID select i).ToList<Image>(); for (int i = 0; i < images.Length; i++) { bool found = false; foreach (Image im in imgs) { if (im.ID == images[i]) { found = true; break; } } if (!found) { newImg.Add(images[i]); } } int[] ids = newImg.ToArray<int>(); List<Image> igs = (from im in db.Image where ids.Contains(im.ID) select im).ToList<Image>(); foreach (Image i in igs) { i.ProductID = product.ID; } db.SaveChanges(); result = true; } } return result; }
public bool CreateProduct(Product product,int[] images) { bool result = false; using (AnanEntities db = new AnanEntities()) { db.Product.Add(product); db.SaveChanges(); if (product.ID>0 && images != null) { List<Image> imgs = (from im in db.Image where images.Contains(im.ID) select im).ToList<Image>(); foreach (Image i in imgs) { i.ProductID = product.ID; } db.SaveChanges(); result = true; } } return result; }
public JsonResult UpdateProduct() { JsonResult res = new JsonResult(); JsonMessage message = new JsonMessage() { Status = "ok", Message = "" }; User user = (User)Session["User"]; ShopManager manager = new ShopManager(user); Product product = new Product(); try { product.ID = int.Parse(Request["product_id"]); product.CategoryID = int.Parse(Request["category_id"]); product.Description = Request["description"]; if (Request["is_new"] == "1") { product.IsNew = 1; } if (Request["is_show"] == "1") { product.ShowFront = 1; } product.Picture = Request["pic"]; product.Price = double.Parse(Request["price"]); product.MarketPrice = double.Parse(Request["mprice"]); product.Quantity = int.Parse(Request["quantity"]); product.Title=Request["title"]; product.UserID = user.ID; string[] images=Request["images"].Split(','); int[] imgIds=new int[images.Length]; for (int i = 0; i < images.Length; i++) { imgIds[i] = int.Parse(images[i]); } if (product.ID == 0) { product.Created = anan.web.Util.DateTimeUtil.ConvertDateTimeToInt(DateTime.Now); if (manager.CreateProduct(product, imgIds)) { message.Message = "产品添加成功"; message.Status = "ok"; } else { message.Status = "failed"; message.Message = "产品添加失败"; } } else { if (manager.UpdateProduct(product, imgIds)) { message.Message = "产品更新成功"; message.Status = "ok"; } else { message.Status = "failed"; message.Message = "产品更新失败"; } } res.Data = message; } catch (Exception ex) { message.Status = "failed"; res.Data = message; } return res; }