Example #1
0
        // создание списка товаров на заказ для вывода в ShowInfoForm
        static public List <ItemOrdersEntity> LoadItemOrdersEntities(int orderID)
        {
            using (var context = new ComputerShopEntities())
            {
                // выборка всех промежуточных сущностей товаров с количеством товара, найденного по ID заказа
                List <OrderItem>        orderIts = context.OrderItems.Where(x => x.OrderID == orderID).Include(x => x.Item).Include("Order").ToList();
                List <ItemOrdersEntity> data     = new List <ItemOrdersEntity>();

                // заполнение форм сущности ItemOrdersEntity данными
                for (int i = 0; i < orderIts.Count(); i++)
                {
                    ItemOrdersEntity ord = new ItemOrdersEntity(
                        item: orderIts[i].Item.ToString(),
                        orderID: orderIts[i].OrderID,
                        quantity: orderIts[i].ItemsQuantity,
                        orderDate: orderIts[i].Order.OrderDate.ToString(),
                        sellerName: orderIts[i].Order.Seller.ToString(),
                        customer: orderIts[i].Order.Customer,
                        customerContact: orderIts[i].Order.CustomerContact,
                        category: orderIts[i].Item.Category.Name
                        );
                    data.Add(ord);
                }
                return(data);
            }
        }
Example #2
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;
            }
        }
Example #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("Невозможно удалить, в категории есть товары!");
            }
        }
Example #4
0
 // создание списка товаров поставщика для вывода в ShowInfoForm
 static public List <Item> ItemsToList(int SupplierID)
 {
     using (var context = new ComputerShopEntities())
     {
         List <Item> original = context.Items.Where(x => x.SupplierID == SupplierID).Include("Category").Include("Supplier").ToList();
         return(original);
     }
 }
Example #5
0
 // поиск категории
 static public Category SearchCategory(string categoryToFind)
 {
     using (var context = new ComputerShopEntities())
     {
         Category category = context.Categories.FirstOrDefault(c => c.Name == categoryToFind);
         return(category);
     }
 }
Example #6
0
 // поиск продавца
 static public Seller SearchSeller(string sellerToFind)
 {
     using (var context = new ComputerShopEntities())
     {
         Seller seller = context.Sellers.FirstOrDefault(c => c.Name == sellerToFind);
         return(seller);
     }
 }
Example #7
0
 // поиск товара по категории и цене
 static public List <Item> SearchItemByCategoryAndPrice(string itemCategory, decimal priceFrom, decimal priceTo)
 {
     using (var context = new ComputerShopEntities())
     {
         var data = context.Items.Where(s => priceTo >= s.Price && s.Price >= priceFrom && s.Category.Name == itemCategory).Include("Category").Include("Supplier").ToList();
         return(data);
     }
 }
Example #8
0
 // все категории
 static public List <Category> AllCategories()
 {
     using (var context = new ComputerShopEntities())
     {
         var data = context.Categories.ToList();
         return(data);
     }
 }
Example #9
0
 // поиск товара по категории
 static public List <Item> SearchItemByCategory(string itemCategory)
 {
     using (var context = new ComputerShopEntities())
     {
         Category category = context.Categories.FirstOrDefault(c => c.Name == itemCategory);
         var      data     = context.Items.Where(x => x.Category.Name == category.Name).Include("Category").Include("Supplier").ToList <Item>();
         return(data);
     }
 }
Example #10
0
        // поиск товара по цене
        static public List <Item> SearchItemByPrice(decimal priceFrom, decimal priceTo)
        {
            using (var context = new ComputerShopEntities())
            {
                var data = context.Items.Where(x => priceTo >= x.Price && x.Price >= priceFrom).Include("Category").Include("Supplier").ToList <Item>();

                return(data);
            }
        }
Example #11
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);
     }
 }
Example #12
0
        // поиск поставщика по имени
        static public List <Supplier> SearchSupplierByName(string itemSupplier)
        {
            using (var context = new ComputerShopEntities())
            {
                Supplier supplier = context.Suppliers.FirstOrDefault(c => c.Name == itemSupplier);
                var      data     = context.Suppliers.Where(x => x.Name == itemSupplier).ToList <Supplier>();

                return(data);
            }
        }
Example #13
0
        // SELLER

        // создание списка продавцов
        static public List <Seller> AllSellers()
        {
            ComputerShopEntities dataEntities = new ComputerShopEntities();

            using (var context = new ComputerShopEntities())
            {
                var data = context.Sellers.ToList <Seller>();
                return(data);
            }
        }
Example #14
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);
     }
 }
Example #15
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);
     }
 }
Example #16
0
        // список всех заказов
        static public List <Order> AllOrders()
        {
            ComputerShopEntities dataEntities = new ComputerShopEntities();

            using (var context = new ComputerShopEntities())
            {
                var data = context.Orders.Include("Seller").ToList <Order>();
                return(data);
            }
        }
Example #17
0
        // ITEMS

        // загрузка всех товаров
        static public List <Item> AllItems()
        {
            ComputerShopEntities dataEntities = new ComputerShopEntities();

            using (var context = new ComputerShopEntities())
            {
                var data = context.Items.Include("Category").Include("Supplier").ToList <Item>();
                return(data);
            }
        }
Example #18
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);
     }
 }
Example #19
0
        // поиск заказа по времени
        static public List <Order> SearchOrderByTime(DateTime dateFrom, DateTime dateTo)
        {
            using (var context = new ComputerShopEntities())
            {
                var data = context.Orders.Where(x => dateTo >= x.OrderDate)
                           .Where(x => x.OrderDate >= dateFrom)
                           .ToList <Order>();

                return(data);
            }
        }
Example #20
0
 // поиск заказа по ID
 static public Order SearchOrderByID(int orderId)
 {
     using (var context = new ComputerShopEntities())
     {
         var order = context.Orders.Find(orderId);
         context.Entry(order).Reference(p => p.Seller).Load();
         //var order = context.Orders.Where(x => x.OrderID == orderId).Include("Seller");
         //var data = context.Items.Where(x => x.Name == itemName).Include("Category").Include("Supplier").ToList<Item>();
         return(order);
     }
 }
Example #21
0
        // обработка нажатия кнопки управления категориями
        private void button3_Click(object sender, EventArgs e)
        {
            // создание экземпляра окна управления категориями
            CategoryOperationForm CategoryForm = new CategoryOperationForm();

            CategoryForm.ShowDialog();

            // отображение обновленного списка категорий в combobox после закрытия формы редактирования категории
            ComputerShopEntities c = new ComputerShopEntities();

            comboBox1.DataSource = c.Categories.ToList();
        }
Example #22
0
        // поиск заказа по продавцу и времени
        static public List <Order> SearchOrderBySellerAndTime(string itemSeller, DateTime dateFrom, DateTime dateTo)
        {
            using (var context = new ComputerShopEntities())
            {
                var data = context.Orders.Where(x => dateTo >= x.OrderDate)
                           .Where(x => x.OrderDate >= dateFrom)
                           .Where(x => x.Seller.Name == itemSeller).Include("Seller")
                           .ToList <Order>();

                return(data);
            }
        }
Example #23
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;
            }
        }
Example #24
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;
            }
        }
Example #25
0
        // обработка нажатия кнопки управления поставщиками
        private void button4_Click(object sender, EventArgs e)
        {
            // поиск поставщика из комбо и назначение текущей сущности поставщика
            MainForm.currentSupplier = DB.SearchSupplier(supplierName: comboBox2.SelectedItem.ToString());
            // создание экземпляра окна управления поставщиками
            SupplierOperationForm SupplierForm = new SupplierOperationForm();

            SupplierForm.Text = "Управление поставщиками";
            SupplierForm.ShowDialog();

            // отображение обновленного списка поставщиков в combobox после закрытия формы редактирования поставщика
            ComputerShopEntities c = new ComputerShopEntities();

            comboBox2.DataSource = c.Suppliers.ToList();
        }
Example #26
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);
     }
 }
Example #27
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);
            }
        }
Example #28
0
        public OrderOperationForm()
        {
            InitializeComponent();

            // заполнение данными комбобоксов
            using (ComputerShopEntities c = new ComputerShopEntities())
            {
                List <Seller> dataSource = DB.AllSellers();

                // удаление админа из списка всех продавцов
                var adminToRemove = dataSource.Single(r => r.SellerID == 1);
                dataSource.Remove(adminToRemove);

                comboBox1.DataSource    = dataSource;
                comboBox1.ValueMember   = "Name";
                comboBox1.DisplayMember = "Name";
            }
        }
Example #29
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);
                }
            }
        }
Example #30
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);
     }
 }