/// <summary> /// 修改商品 /// </summary> /// <param name="dto"></param> /// <returns></returns> public bool Update(UpdateGoodsDto dto) { using (var commodityDbContext = new CommodityDbContext()) { dto.Price = System.Decimal.Round(System.Decimal.Floor(dto.Price * 100) / 100, 2); //判断标签的id是否存在 if (commodityDbContext.LabelRepos.Where(o => dto.Tags.Contains(o.Id)).Count() != dto.Tags.Length) { throw new Exception("有标签不存在"); } //修改Goods表 var entity = commodityDbContext.GoodsRepos.Where(o => o.Id == dto.Id).FirstOrDefault(); if (entity == null) { throw new Exception("商品不存在"); } entity.Name = dto.Name; entity.Pinyin = PinYin.ConvertCh(dto.Name).ToLower(); entity.Price = dto.Price; entity.Describe = dto.Describe; //删除label_goods表中所有与该商品有关的记录 commodityDbContext.Database.ExecuteSqlCommand(@"delete from label_goods where goods_id = @p0", dto.Id); //往label_goods表中添加该商品的标签 foreach (var Tag in dto.Tags) { commodityDbContext.LabelGoodsRepos.Add(new LabelGoodsRepo() { Goods_id = entity.Id, Label_id = Tag }); } return(commodityDbContext.SaveChanges() > 0); } }
/// <summary> /// 添加商品 /// </summary> /// <param name="dto"></param> /// <returns></returns> public bool Create(CreateGoodsDto dto) { using (var commodityDbContext = new CommodityDbContext()) { var tran = commodityDbContext.Database.BeginTransaction(); try { dto.Price = System.Decimal.Round(System.Decimal.Floor(dto.Price * 100) / 100, 2); //若商品编号重复,返回false if (commodityDbContext.GoodsRepos.Any(o => o.Number == dto.Number)) { throw new Exception("商品编号重复"); } //判断标签的id是否存在 if (commodityDbContext.LabelRepos.Where(o => dto.Tags.Contains(o.Id)).Count() != dto.Tags.Length) { throw new Exception("有标签不存在"); } GoodsRepo goods = new GoodsRepo() { Number = dto.Number, Name = dto.Name, Pinyin = PinYin.ConvertCh(dto.Name).ToLower(), Price = dto.Price, Describe = dto.Describe, Updatetime = DateTime.Now }; commodityDbContext.GoodsRepos.Add(goods); commodityDbContext.SaveChanges(); //往label_goods表中添加该商品的标签 foreach (var Tag in dto.Tags) { commodityDbContext.LabelGoodsRepos.Add(new LabelGoodsRepo() { Goods_id = goods.Id, Label_id = Tag }); } return(commodityDbContext.SaveChanges() > 0); } catch (Exception ex) { tran.Rollback(); throw ex; } } }