public ActionResult Create([Bind(Include = "DueDate,Recipient, Taxes")] Invoice invoice) { try { if (ModelState.IsValid) { ComposeTaxCalculator(); invoice.CreationDate = DateTime.Now; invoice.TotalCost = invoice.invoiceTotalCost(); invoice.TotalCostWithTax = calculator.CalculateTax(invoice.Taxes, invoice.TotalCost); db.Invoices.Add(invoice); db.SaveChanges(); return(RedirectToAction("Edit", new { id = invoice.Id })); } } catch (DataException) { ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator."); } return(View(invoice)); }
public void fillWholeStore(int quantity) { using (warehouseContext) { foreach (var item in warehouseContext.wItems.ToList()) { storeItems storeItem = new storeItems { Name = " ", Quantity = 0, Manufacturer = " ", Description = " ", Price = 0 }; storeItem.Name = item.Name; storeItem.Quantity += quantity; storeItem.Manufacturer = item.Manufacturer; storeItem.Price = item.Price; storeItem.Description = item.Description; item.Quantity -= quantity; storeContext.storeItems.Add(storeItem); warehouseContext.SaveChanges(); storeContext.SaveChanges(); } } }
public StockMovementActionResultModel Create(string productCode, [FromBody] CreateStockmovementModel model) { if (!ModelState.IsValid) { throw new ValidationException(ModelState); } var product = _ctx.Set <ProductEntity>().SingleOrDefault(e => e.Code == productCode); if (product == null) { throw new NotFoundException(); } var stockMovement = new StockMovementEntity { Price = product.Price, Quantity = model.Quantity, CreatedOn = DateTimeOffset.Now, CreatedBy = this.GetUserName(), Product = product }; _ctx.Add(stockMovement); _ctx.SaveChanges(); return(new StockMovementActionResultModel { Id = stockMovement.Id }); }
public ActionResult Create(Thing thing, FormCollection form) { if (ModelState.IsValid) { var c1 = form["ta_includs"].Split(',').ToList(); foreach (var t in c1) { thing.Includes.Add( db.Things.Where(x => x.Name == t).FirstOrDefault()); } db.Things.Add(thing); db.SaveChanges(); return(RedirectToAction("Index")); } else { //Thing th = new Thing { Name = form["Includes"].ToString() }; //var c = form["ta_includs"]; //var errors = ModelState.Values.SelectMany(v => v.Errors); return(View(thing)); } }
public IActionResult GetItemRequest([FromHeader(Name = "Cookie")] string userCookie, [FromRoute] string id) { var item = _context.Items.Include(i => i.User).SingleOrDefault(x => x.Id == id); if (item != null) { var principal = HttpContext.User as ClaimsPrincipal; var userId = principal?.Claims .First(c => c.Type == ClaimTypes.NameIdentifier); if (item.User != null) { var returnEvent = new EventLog() { Id = Guid.NewGuid().ToString(), Type = Model.Enums.EventType.Return, Item = item, User = item.User, Time = DateTime.Now }; _context.EventLogs.Add(returnEvent); } var user = _context.Users.Single(x => x.Id == userId.Value); item.User = user; var getEvent = new EventLog() { Id = Guid.NewGuid().ToString(), Type = Model.Enums.EventType.Get, Item = item, User = user, Time = DateTime.Now }; _context.EventLogs.Add(getEvent); _context.SaveChanges(); return(new JsonResult("ok")); } else { return(NotFound()); } }
/// <inheritdoc /> public Notification Add(Notification notification) { var storingNotification = new StoringNotification(notification); _db.Notifications.Add(storingNotification); _db.SaveChanges(); return(storingNotification); }
public void AddEntry(string userid, string text) { context.LogEntries.Add(new LogEntry() { Time = DateTime.UtcNow.ToLocalTime(), EmployeeId = userid, Text = text, }); context.SaveChanges(); }
//Create Supplier public SupplierModels newSupplier(SupplierModels supplier) { if (ModelState.IsValid) { _db.SupplierModels.Add(supplier); _db.SaveChanges(); } return(supplier); }
public ActionResult Create([Bind(Include = "ID,Brand,Make,Price,Count,FreeShipping,Description")] Product product) { if (ModelState.IsValid) { db.Products.Add(product); db.SaveChanges(); return(RedirectToAction("Details", new { id = product.ID })); } return(View(product)); }
public ActionResult Create([Bind(Include = "Id,Name,Category,Price,Count,Description")] Product product) { if (ModelState.IsValid) { db.Products.Add(product); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(product)); }
public ActionResult Create([Bind(Include = "Id,Name,Price,Quantity,Category,Description")] Product product) { if (ModelState.IsValid) { db.Products.Add(product); db.SaveChanges(); return(RedirectToAction("Create", new { product.Id })); } return(View(product)); }
//Create new log public LogModels log3(SearchIndex search) { LogModels log = new LogModels { Type = "3", Description = "There was new search in Laptop section for " + search.Name + ".", Date = DateTime.Now }; _db.LogModels.Add(log); _db.SaveChanges(); return(log); }
public IActionResult Create([FromBody] CreateProductModel model) { if (ModelState.IsValid) { var productsSet = _ctx.Set <ProductEntity>(); if (productsSet.Any(e => e.Code.Equals(model.Code.Trim(), StringComparison.InvariantCultureIgnoreCase))) { return(Conflict(new { Message = "Código duplicado" })); } if (productsSet.Any(e => e.Name.Equals(model.Name.Trim(), StringComparison.InvariantCultureIgnoreCase))) { return(Conflict(new { Message = "Nome duplicado" })); } var now = DateTimeOffset.Now; var username = GetUserName(); var product = new ProductEntity { Code = model.Code, Name = model.Name, Description = model.Description, Price = model.Price, CreatedOn = now, CreatedBy = username, UpdatedOn = now, UpdatedBy = username, Version = Guid.NewGuid() }; productsSet.Add(product); _ctx.SaveChanges(); return(Json(new CreateProductResultModel { Id = product.Id })); } return(UnprocessableEntity(new { Message = "Entidade com dados inválidos", ModelState = ModelState.Select(e => new { Key = e.Key, Value = e.Value.Errors }) })); }
public void fillWholeStore(int quantity) { if (!storeContext.storeItems.Any()) { using (warehouseContext) { foreach (var item in warehouseContext.wItems.ToList()) { storeItems storeItem = new storeItems { Name = " ", Quantity = 0, Manufacturer = " ", Description = " ", Price = 0 }; if (item.Quantity > quantity) //adding check for warehouse availability { storeItem.Name = item.Name; storeItem.Quantity += quantity; storeItem.Manufacturer = item.Manufacturer; storeItem.Price = item.Price; storeItem.Description = item.Description; item.Quantity -= quantity; storeContext.storeItems.AddAsync(storeItem); } warehouseContext.SaveChangesAsync(); storeContext.SaveChangesAsync(); } } } else { using (storeContext) { foreach (var itm in storeContext.storeItems.ToList()) { var w = warehouseContext.wItems.FirstOrDefault(i => i.Name == itm.Name); if (w.Quantity > quantity) { itm.Quantity += quantity; w.Quantity -= quantity; warehouseContext.wItems.Update(w); storeContext.SaveChanges(); warehouseContext.SaveChanges(); } } } } }
public Item AddOrUpdateItem(ModelItem item, string userid) { Employee employee = context.Employees.FirstOrDefault(e => e.Id == userid); var dbItem = context.Items.Include(i => i.Container).FirstOrDefault(i => i.Id == item.Id); if (dbItem == null) { dbItem = new Item() { Name = item.Name, Description = item.Description, Count = item.Count, ContainerId = item.ContainerId }; context.Items.Add(dbItem); string containername = context.Containers.FirstOrDefault(c => c.Id == item.ContainerId).Name; logService.AddEntry(userid, $"Added {item.Count} item(s) {item.Name} to container {containername}"); } else { string newcontainername = context.Containers.FirstOrDefault(c => c.Id == item.ContainerId).Name; if (dbItem.ContainerId != item.ContainerId) { logService.AddEntry(userid, $"Moved {item.Name} from {dbItem.Container.Name} to {newcontainername}"); } if (dbItem.Name != item.Name) { logService.AddEntry(userid, $"Renamed {dbItem.Name} to {item.Name}"); } if (dbItem.Count != item.Count) { logService.AddEntry(userid, $"{dbItem.Name} count changed from {dbItem.Count} to {item.Count}"); } dbItem.Container.LastEmployee = employee; dbItem.Name = item.Name; dbItem.Description = item.Description; dbItem.Count = item.Count; dbItem.ContainerId = item.ContainerId; } Container newContainer = context.Containers.FirstOrDefault(c => c.Id == dbItem.ContainerId); if (newContainer != null) { newContainer.LastEmployee = employee; } context.SaveChanges(); return(dbItem); }
public IActionResult NewOrder([FromBody] Order newOrder) { if (newOrder.Id != 0) { return(BadRequest()); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } context.Orders.Add(newOrder); context.SaveChanges(); return(Created("", newOrder)); }
public IActionResult NewProduct([FromBody] Product newProduct) { if (newProduct.Id != 0) { return(BadRequest()); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } context.Products.Add(newProduct); context.SaveChanges(); return(Created("", newProduct)); }
public Control CallAddProductControl(string productScanCode, WarehouseContext dbcontext, Action <Product> createCallback = null) { var formControl = FormControlHelper.CreateFormControl(); var product = new Product(); product.ScanCode = productScanCode; formControl.RenderForm(product, false); formControl.ConfirmButton.Content = "录入产品"; formControl.SubmitCallback = (d) => { try { dbcontext.Products.Add((Product)d); dbcontext.SaveChanges(); if (createCallback != null) { createCallback((Product)d); } } catch (Exception ex) { //TODO: handle exception formControl.SetErrorMsgManually("ScanCode", "此产品扫码已存在"); } }; return(formControl); }
private void DeleteUser_Clicked(object sender, RoutedEventArgs e) { var data = ((Button)sender).DataContext as User; if (data != null) { var result = MessageBox.Show( string.Format("你是否决定要删除用户'{0}'?", data.Name), "操作警告", MessageBoxButton.OKCancel, MessageBoxImage.Warning); if (result == MessageBoxResult.OK) { try { using (var dbcontext = new WarehouseContext()) { var deluser = dbcontext.Users.Find(((User)data).UserId); dbcontext.Users.Remove(deluser); dbcontext.SaveChanges(); edit_br.Child = null; ReloadUserGrid(); } } catch (Exception ex) { WindowMgr.SendNotification("删除操作失败。", NotificationLevel.Error); } } } }
public Control CallCreateUserControl(Action <User> createCallback = null) { var formControl = FormControlHelper.CreateFormControl(); formControl.RenderForm(new User(), false); formControl.ConfirmButton.Content = "创建用户"; formControl.SubmitCallback = (d) => { using (var dbcontext = new WarehouseContext()) { try { dbcontext.Users.Add((User)d); dbcontext.SaveChanges(); if (createCallback != null) { createCallback((User)d); } } catch (Exception ex) { //TODO: handle exception formControl.SetErrorMsgManually("Username", "此用户名已存在,请更换"); } } }; return(formControl); }
public CResult <bool> AddSpeedChangeBoxType(string speedChangeBoxName) { if (string.IsNullOrWhiteSpace(speedChangeBoxName)) { return(new CResult <bool>(false, ErrorCode.ParameterError)); } using (var db = new WarehouseContext()) { var repository = RepositoryIoc.GetSpeedChangeBoxTypeRepository(db); if (repository.Count(r => r.SpeedChangeBoxName == speedChangeBoxName) > 0) { return(new CResult <bool>(false, ErrorCode.SpeedChangeBoxHasExist)); } var speedChangeBox = new SpeedChangeBoxType(); speedChangeBox.SpeedChangeBoxName = speedChangeBoxName; repository.Insert(speedChangeBox); if (db.SaveChanges() > 0) { return(new CResult <bool>(true)); } else { return(new CResult <bool>(false, ErrorCode.SaveDbChangesFailed)); } } }
public static string Edit(UserDTO user) { using (WarehouseContext db = new WarehouseContext()) { string error = null; var toModify = db.Users.Where(x => x.Id == user.Id).FirstOrDefault(); toModify.FirstName = user.FirstName; toModify.LastName = user.LastName; toModify.Email = user.Email; toModify.PhoneNumber = user.PhoneNumber; toModify.BirthDate = user.BirthDate; var context = new ValidationContext(toModify, null, null); var result = new List <ValidationResult>(); Validator.TryValidateObject(toModify, context, result, true); foreach (var x in result) { error = error + x.ErrorMessage + "\n"; } if (error == null) { db.SaveChanges(); } return(error); } }
public static string Add(InventoryDTO inventory) { using (WarehouseContext db = new WarehouseContext()) { string error = null; Inventory newInventory = new Inventory(); newInventory.Id = inventory.Id; newInventory.ItemFrom = inventory.ItemFrom; newInventory.ItemTo = inventory.ItemTo; newInventory.DateOfArrival = inventory.DateOfArrival; newInventory.DateToSend = inventory.DateToSend; newInventory.Weight = inventory.Weight; newInventory.Status = inventory.Status; newInventory.Description = inventory.Description; var context = new ValidationContext(newInventory, null, null); var result = new List <ValidationResult>(); Validator.TryValidateObject(newInventory, context, result, true); foreach (var x in result) { error = error + x.ErrorMessage + "\n"; } if (error == null) { db.Inventory.Add(newInventory); db.SaveChanges(); } return(error); } }
public static string Add(ReturnDTO returnVar) { using (WarehouseContext db = new WarehouseContext()) { string error = null; Return newReturn = new Return(); newReturn.Id = returnVar.Id; newReturn.Client = returnVar.Client; newReturn.Date = returnVar.Date; newReturn.Description = returnVar.Description; newReturn.Attachment = returnVar.Attachment; var context = new ValidationContext(newReturn, null, null); var result = new List <ValidationResult>(); Validator.TryValidateObject(newReturn, context, result, true); foreach (var x in result) { error = error + x.ErrorMessage + "\n"; } if (error == null) { db.Returns.Add(newReturn); db.SaveChanges(); } return(error); } }
public static string Add(UserDTO user) { using (WarehouseContext db = new WarehouseContext()) { string error = null; User newUser = new User(); newUser.FirstName = user.FirstName; newUser.LastName = user.LastName; newUser.Email = user.Email; newUser.PhoneNumber = user.PhoneNumber; newUser.BirthDate = user.BirthDate; var context = new ValidationContext(newUser, null, null); var result = new List <ValidationResult>(); Validator.TryValidateObject(newUser, context, result, true); foreach (var x in result) { error = error + x.ErrorMessage + "\n"; } if (error == null) { db.Users.Add(newUser); db.SaveChanges(); } return(error); } }
public static string Edit(ReturnDTO returnVar) { using (WarehouseContext db = new WarehouseContext()) { string error = null; var toModify = db.Returns.Where(x => x.Id == returnVar.Id).FirstOrDefault(); toModify.Id = returnVar.Id; toModify.Client = returnVar.Client; toModify.Date = returnVar.Date; toModify.Description = returnVar.Description; toModify.Attachment = returnVar.Attachment; var context = new ValidationContext(toModify, null, null); var result = new List <ValidationResult>(); Validator.TryValidateObject(toModify, context, result, true); foreach (var x in result) { error = error + x.ErrorMessage + "\n"; } if (error == null) { db.SaveChanges(); } return(error); } }
public static string Edit(InventoryDTO inventory) { using (WarehouseContext db = new WarehouseContext()) { string error = null; var toModify = db.Inventory.Where(x => x.Id == inventory.Id).FirstOrDefault(); toModify.Id = inventory.Id; toModify.ItemFrom = inventory.ItemFrom; toModify.ItemTo = inventory.ItemTo; toModify.DateOfArrival = inventory.DateOfArrival; toModify.DateToSend = inventory.DateToSend; toModify.Weight = inventory.Weight; toModify.Status = inventory.Status; toModify.Description = inventory.Description; var context = new ValidationContext(toModify, null, null); var result = new List <ValidationResult>(); Validator.TryValidateObject(toModify, context, result, true); foreach (var x in result) { error = error + x.ErrorMessage + "\n"; } if (error == null) { db.SaveChanges(); } return(error); } }
public CResult <bool> DelSpeedChangeBox(int speedChangeID) { if (speedChangeID <= 0) { return(new CResult <bool>(false, ErrorCode.ParameterError)); } using (var db = new WarehouseContext()) { var repository = RepositoryIoc.GetSpeedChangeBoxTypeRepository(db); var speedChange = repository.FirstOrDefault(r => r.SpeedChangeBoxTypeID == speedChangeID, CommonHelper.GetPropName <SpeedChangeBoxType>(r => r.TwoDimensioncodes)); if (speedChange.TwoDimensioncodes.Count() > 0) { return(new CResult <bool>(false, ErrorCode.SpeedChangeHasTwoDimensioncodes)); } repository.Delete(speedChange); if (db.SaveChanges() > 0) { return(new CResult <bool>(true)); } else { return(new CResult <bool>(false, ErrorCode.SaveDbChangesFailed)); } } }
public static void Main(string[] args) { using (WarehouseContext db = new WarehouseContext()) { // создаем два объекта product Product product1 = new Product("морковка", "0000000001", 10, 15); Product product2 = new Product("картошка", "0000000002", 15, 20); Product product3 = new Product("огурец", "0000000002", 25, 30); // добавляем их в бд db.Products.Add(product1); db.Products.Add(product2); db.SaveChanges(); Console.WriteLine("Объекты успешно сохранены"); // получаем объекты из бд и выводим на консоль var products = db.Products; Console.WriteLine("Список объектов:"); foreach (Product p in products) { Console.WriteLine("{0}-{1}: Объем:{2}, Вес:{3}", p.VendorСode, p.Name, p.Volume, p.Weight); } } Console.Read(); //CreateHostBuilder(args).Build().Run(); }
//Save this users details after editing public UserModels saveUser(UserModels userModels) { _db.Entry(userModels).State = EntityState.Modified; userModels.DateModified = DateTime.Now; _db.SaveChanges(); return(userModels); }
public static void AddSampleData() { using (var dbcontext = new WarehouseContext()) { try { var user1 = new User() { Name = "二娃", Username = "******", Password = "******", IdentificationNumber = "310392198305114344", PhoneNumber = "13543776409", Company = "梁山", Department = "库房管理部", Memo = "(●'◡'●)" }; dbcontext.Users.Add(user1); var tg = new TagGroup() { Name = "功能" }; dbcontext.TagGroups.Add(tg); var tag1 = new Tag() { Name = "食品", Group = tg }; dbcontext.Tags.Add(tag1); var tag2 = new Tag() { Name = "书籍", Group = tg }; dbcontext.Tags.Add(tag2); var tag3 = new Tag() { Name = "酒水", Group = tg }; dbcontext.Tags.Add(tag3); var product = new Product() { Name = "乐事薯片100g(清新黄瓜)", ScanCode = "111" }; dbcontext.Products.Add(product); var good = new Goods() { GoodsCode = "111", InboundDate = DateTime.Now, Product = product, State = GoodsState.Inbounding }; dbcontext.Goods.Add(good); dbcontext.SaveChanges(); } catch { // do nothing } } using (var dbcontext = new WarehouseContext()) { var item = dbcontext.Goods.First(); } }