Ejemplo n.º 1
0
        static public void EditOrder(int orderID)
        {
            try
            {
                using (var context = new ComputerShopEntities())
                {
                    // поиск Order-a для редактирования
                    var original = context.Orders.Single(x => x.OrderID == orderID);
                    // временное поле имени продавца
                    string sellerTempName = MainForm.currentItemOrdersEntities[0].SellerName;
                    Seller seller         = context.Sellers.FirstOrDefault(x => x.Name == sellerTempName);
                    // изменение полей Order-a
                    if (original != null)
                    {
                        original.OrderDate       = Convert.ToDateTime(MainForm.currentItemOrderEntity.OrderDate);
                        original.Customer        = MainForm.currentItemOrderEntity.Customer;
                        original.CustomerContact = MainForm.currentItemOrderEntity.CustomerContact;
                        original.Seller          = seller;
                    }
                    context.SaveChanges();

                    // редактирование привязанных к созданному Order OrderItems из списка
                    // удаление всех старых сущностей товаров заказа
                    original.OrderItems.Clear();
                    context.SaveChanges();

                    // добавление новых сущностей товаров в список товара заказа
                    foreach (ItemOrdersEntity itOrd in MainForm.currentItemOrdersEntities)
                    {
                        OrderItem temp = new OrderItem();
                        temp.ItemID        = SearchItemByNameOrID(itemName: itOrd.Item)[0].ItemID;
                        temp.OrderID       = itOrd.OrderID;
                        temp.ItemsQuantity = itOrd.Quantity;
                        original.OrderItems.Add(temp);
                    }
                    context.SaveChanges();
                    MessageBox.Show($"Обновлен заказ: ID{orderID} на {MainForm.currentItemOrdersEntities.Count} товара", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    foreach (var ve in eve.ValidationErrors)
                    {
                        MessageBox.Show(ve.ErrorMessage);
                    }
                }
                throw;
            }
        }
Ejemplo n.º 2
0
        // ORDERS

        // создание заказа с товарами и привязанным количеством
        static public void AddOrder(DateTime orderDate, string customer, string customerContact, string seller)
        {
            try
            {
                using (var context = new ComputerShopEntities())
                {
                    Seller sellerEntry = context.Sellers.FirstOrDefault(c => c.Name == seller);

                    // создание нового Order-a
                    var orderEntry = new Order()
                    {
                        OrderDate       = orderDate,
                        Customer        = customer,
                        CustomerContact = customerContact,
                        Seller          = sellerEntry
                    };
                    context.Orders.Add(orderEntry);
                    context.SaveChanges();
                    int orderId = orderEntry.OrderID;
                    //orderEntry.Seller = searchSeller(MainForm.currentItemOrdersEntities[0].SellerName);

                    // создание привязанных к созданному Order OrderItems из списка
                    foreach (ItemOrdersEntity ordItem in MainForm.currentItemOrdersEntities)
                    {
                        var orderItemsEntry = new OrderItem()
                        {
                            // нахождение ItemID по имени Item
                            ItemID        = DB.SearchItemByNameOrID(itemName: ordItem.Item)[0].ItemID,
                            OrderID       = orderId,
                            ItemsQuantity = ordItem.Quantity,
                        };
                        context.OrderItems.Add(orderItemsEntry);
                        context.SaveChanges();
                    }
                    MessageBox.Show($"Добавлен заказ: ID{orderId} на {MainForm.currentItemOrdersEntities.Count} товара", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    foreach (var ve in eve.ValidationErrors)
                    {
                        MessageBox.Show(ve.ErrorMessage);
                    }
                }
                throw;
            }
        }
Ejemplo n.º 3
0
        // удаление категории
        static public void RemoveCategory(string categoryName)
        {
            try
            {
                using (var context = new ComputerShopEntities())
                {
                    var original = context.Categories.FirstOrDefault(a => a.Name == categoryName);
                    // проверка привязанных к категории товаров
                    if (original.Items.Count > 0)
                    {
                        foreach (Item it in original.Items)
                        {
                            it.Category = context.Categories.FirstOrDefault(a => a.Name == "no category");
                        }
                    }

                    context.Categories.Remove(context.Categories.FirstOrDefault(a => a.Name == categoryName));
                    context.SaveChanges();
                    MessageBox.Show($"Категория {categoryName} удалена!", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (System.Data.Entity.Infrastructure.DbUpdateException e)
            {
                MessageBox.Show("Невозможно удалить, в категории есть товары!");
            }
        }
Ejemplo n.º 4
0
        // добавление товара в БД
        static public void AddItem(string name, decimal price, string category, string supplier)
        {
            try
            {
                using (var context = new ComputerShopEntities())
                {
                    Category categoryEntry = context.Categories.FirstOrDefault(c => c.Name == category);
                    Supplier supplierEntry = context.Suppliers.FirstOrDefault(c => c.Name == supplier);

                    context.Items.Add(new Item {
                        Name     = name,
                        Price    = price,
                        Category = categoryEntry,
                        Supplier = supplierEntry
                    });
                    context.SaveChanges();
                    MessageBox.Show($"Добавлен товар: {name}", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            // отлавливание ошибок
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    foreach (var ve in eve.ValidationErrors)
                    {
                        MessageBox.Show(ve.ErrorMessage);
                    }
                }
                throw;
            }
        }
Ejemplo n.º 5
0
 // изменение продавца
 static public void EditSeller(Seller editSeller)
 {
     using (var context = new ComputerShopEntities())
     {
         var original = context.Sellers.Find(editSeller.SellerID);
         context.Entry(original).CurrentValues.SetValues(editSeller);
         context.SaveChanges();
         MessageBox.Show($"Продавец {editSeller.Name} обновлен!", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
 }
Ejemplo n.º 6
0
 // редактирование поставщика
 static public void EditSupplier(Supplier toEdit)
 {
     using (var context = new ComputerShopEntities())
     {
         var original = context.Suppliers.Find(toEdit.SupplierID);
         context.Entry(original).CurrentValues.SetValues(toEdit);
         context.SaveChanges();
         MessageBox.Show($"Поставщик {toEdit.Name} обновлен!", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
 }
Ejemplo n.º 7
0
 // редактирование категории
 static public void EditCategory(Category toEdit)
 {
     using (var context = new ComputerShopEntities())
     {
         var original = context.Categories.Find(toEdit.CategoryID);
         context.Entry(original).CurrentValues.SetValues(toEdit);
         context.SaveChanges();
         MessageBox.Show($"Категория {toEdit.Name} обновлена!", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
 }
Ejemplo n.º 8
0
 // удаление заказа
 static public void RemoveOrder(ItemOrdersEntity toRemove)
 {
     using (var context = new ComputerShopEntities())
     {
         var original = context.Orders.Find(toRemove.OrderID);
         context.OrderItems.RemoveRange(original.OrderItems);
         context.Entry(original).State = EntityState.Deleted;
         context.SaveChanges();
         MessageBox.Show("Заказ с ID " + toRemove.OrderID + " удален из базы данных!", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
 }
Ejemplo n.º 9
0
 // удаление продавца
 static public void RemoveSeller(string sellerName)
 {
     try
     {
         using (var context = new ComputerShopEntities())
         {
             var original = context.Sellers.FirstOrDefault(a => a.Name == sellerName);
             context.Sellers.Remove(context.Sellers.FirstOrDefault(a => a.Name == sellerName));
             context.SaveChanges();
             MessageBox.Show($"Продавец {sellerName} удален!", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Information);
         }
     }
     catch (System.Data.Entity.Infrastructure.DbUpdateException e)
     {
         MessageBox.Show($"За продавцом числятся заказы, удаление невозможно!", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Ejemplo n.º 10
0
        // CATEGORY

        // добавление категории
        static public void AddCategory(string categoryName)
        {
            using (var context = new ComputerShopEntities())
            {
                // проверка название категории на существование в БД
                if (SearchCategory(categoryName) != null)
                {
                    MessageBox.Show($"Категория {categoryName} уже существует!", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                context.Categories.Add(new Category {
                    Name = categoryName
                });
                context.SaveChanges();
                MessageBox.Show($"Добавлена категория: {categoryName}", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Ejemplo n.º 11
0
        // добавление поставщика
        static public void AddSupplier(Supplier newSupplier)
        {
            using (var context = new ComputerShopEntities())
            {
                // проверка названия поставщика на существование в БД
                if (SearchSupplier(supplierName: newSupplier.Name) == null)
                {
                    context.Suppliers.Add(newSupplier);
                    context.SaveChanges();

                    MessageBox.Show($"Добавлен поставщик:  {newSupplier.Name}", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show($"Такой поставщик уже существует!", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Ejemplo n.º 12
0
 // удаление товара
 static public void RemoveItem(Item removeEntry)
 {
     try
     {
         using (var context = new ComputerShopEntities())
         {
             var original = context.Items.Remove(context.Items.Single(a => a.ItemID == removeEntry.ItemID));
             context.Entry(original).Collection(r => r.OrderItems).CurrentValue = null;
             context.Entry(original).State = EntityState.Deleted;
             context.SaveChanges();
             MessageBox.Show($"{removeEntry.Name} удален из базы!", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Information);
         }
     }
     catch
     {
         MessageBox.Show("На товар оформлен заказ!", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Ejemplo n.º 13
0
 // удаление поставщика
 static public void RemoveSupplier(Supplier toRemove)
 {
     try
     {
         using (var context = new ComputerShopEntities())
         {
             context.Suppliers.Remove(context.Suppliers.FirstOrDefault(a => a.Name == toRemove.Name));
             // удаление связанных товаров
             //var original = context.Suppliers.Find(toRemove.SupplierID);
             //context.Items.RemoveRange(original.Items);
             //context.Entry(original).State = EntityState.Deleted;
             context.SaveChanges();
             MessageBox.Show($"Поставщик {toRemove.Name} удален!", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Information);
         }
     }
     catch (System.Data.Entity.Infrastructure.DbUpdateException e)
     {
         MessageBox.Show("Невозможно удалить, к поставщику привязаны товары!", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Ejemplo n.º 14
0
        // редактирование товара
        static public void EditItem()
        {
            using (var context = new ComputerShopEntities())
            {
                var original = context.Items.Single(x => x.ItemID == MainForm.currentItem.ItemID);

                Category categoryEntry = context.Categories.FirstOrDefault(c => c.Name == MainForm.currentItem.Category.Name);
                Supplier supplierEntry = context.Suppliers.FirstOrDefault(c => c.Name == MainForm.currentItem.Supplier.Name);

                if (original != null)
                {
                    original.Name     = MainForm.currentItem.Name;
                    original.Price    = MainForm.currentItem.Price;
                    original.Category = categoryEntry;
                    original.Supplier = supplierEntry;
                }
                ;
                context.SaveChanges();
                MessageBox.Show($"{MainForm.currentItem.Name} обновлен!", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Ejemplo n.º 15
0
        // добавление продавца
        static public void AddSeller(string name, string contacts, string accountType, string pass)
        {
            using (var context = new ComputerShopEntities())
            {
                // проверка имени продавца на существование в БД
                if (SearchSeller(sellerToFind: name) == null)
                {
                    context.Sellers.Add(new Seller
                    {
                        Name        = name,
                        Contacts    = contacts,
                        AccountType = accountType,
                        Password    = pass
                    });
                    context.SaveChanges();

                    MessageBox.Show($"Добавлен аккаунт:  {name}", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show($"Такой аккаунт уже существует!", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }