Example #1
0
        private void InitializeProducts()
        {
            var timer = Stopwatch.StartNew();

            if (_db.Products.Any())
            {
                _Logger.LogInformation("Инициализация БД товарами не требуется");
                return;
            }

            _Logger.LogInformation("Инициализация товаров...");

            _Logger.LogInformation("Добавление секций...");
            using (_db.Database.BeginTransaction())
            {
                _db.Sections.AddRange(TestData.Sections);

                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Sections] ON");
                _db.SaveChanges();  // все изменения заносятся в базу данных
                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Sections] OFF");

                _db.Database.CommitTransaction();
            }
            _Logger.LogInformation("Секции успешно добавлены в БД");


            _Logger.LogInformation("Добавление брендов...");
            using (_db.Database.BeginTransaction())
            {
                _db.Brands.AddRange(TestData.Brands);

                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Brands] ON");
                _db.SaveChanges();  // все изменения заносятся в базу данных
                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Brands] OFF");

                _db.Database.CommitTransaction();
            }
            _Logger.LogInformation("Бренды успешно добавлены в БД");


            _Logger.LogInformation("Добавление товаров...");
            using (_db.Database.BeginTransaction())
            {
                _db.Products.AddRange(TestData.Products);

                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Products] ON");
                _db.SaveChanges();  // все изменения заносятся в базу данных
                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Products] OFF");

                _db.Database.CommitTransaction();
            }
            _Logger.LogInformation("Товары успешно добавлены в БД");


            _Logger.LogInformation("Инициализация товаров выполнена успешно  ({0:0.0###})",
                                   timer.Elapsed.TotalSeconds);
        }
        public ActionResult Create([Bind(Include = "CartItemId,ArticleName,Quantity")] CartItem cartItem)
        {
            if (ModelState.IsValid)
            {
                db.CartItems.Add(cartItem);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(cartItem));
        }
        public ActionResult Create([Bind(Include = "CustomerId,FirstName,LastName,Adress,ZipCode,Email,PhoneNumber")] Customer customer)
        {
            if (ModelState.IsValid)
            {
                db.Customers.Add(customer);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(customer));
        }
        public ActionResult Create([Bind(Include = "ArticleId,ArticleName,Description,Price,Image,Stock")] Product product)
        {
            if (ModelState.IsValid)
            {
                db.Products.Add(product);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(product));
        }
Example #5
0
        public int Add(Employee employee)
        {
            if (employee is null)
            {
                throw new ArgumentNullException(nameof(employee));
            }

            _db.Add(employee);

            _db.SaveChanges();

            _Logger.LogInformation($"Сотрудник id:{employee} добавлен");

            return(employee.Id);
        }
Example #6
0
        private void InitializeProducts()
        {
            var timer = Stopwatch.StartNew();

            if (_db.Products.Any())
            {
                _Logger.LogInformation("Добавление исходных данных в БД не требуется");
                return;
            }

            _Logger.LogInformation("Добавление секций... {0} мс", timer.ElapsedMilliseconds);
            using (_db.Database.BeginTransaction())
            {
                _db.Sections.AddRange(TestData.Sections);

                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Sections] ON");
                _db.SaveChanges();
                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Sections] OFF");

                _db.Database.CommitTransaction();
            }

            _Logger.LogInformation("Добавление брендов...");
            using (_db.Database.BeginTransaction())
            {
                _db.Brands.AddRange(TestData.Brands);

                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Brands] ON");
                _db.SaveChanges();
                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Brands] OFF");

                _db.Database.CommitTransaction();
            }

            _Logger.LogInformation("Добавление товаров...");
            using (_db.Database.BeginTransaction())
            {
                _db.Products.AddRange(TestData.Products);

                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Products] ON");
                _db.SaveChanges();
                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Products] OFF");

                _db.Database.CommitTransaction();
            }

            _Logger.LogInformation("Добавление исходных данных выполнено успешно за {0} мс", timer.ElapsedMilliseconds);
        }
Example #7
0
        private void InitializeProducts()
        {
            var timer = Stopwatch.StartNew();

            if (_Db.Products.Any())
            {
                _Logger.LogInformation("---> Инициализация товаров не требуется.");
                return;
            }

            _Logger.LogInformation("---> Инициализация товаров...");

            ConvertData();

            using (_Db.Database.BeginTransaction())
            {
                _Logger.LogInformation("---> Добавление данных в БД...");
                _Db.Products.AddRange(TestData.Products);
                _Db.Brands.AddRange(TestData.Brands);
                _Db.Sections.AddRange(TestData.Sections);

                _Db.SaveChanges();

                _Db.Database.CommitTransaction();
                _Logger.LogInformation($"---> Добавление данных в БД завершено за {timer.Elapsed.TotalSeconds} c.");
            }
        }
Example #8
0
        void TableInitWiaTransaction <T>(DbContext context, IEnumerable <T> data, bool isClearIds = false) where T : BaseEntity
        {
            var table = context.Set <T>();

            if (table.Any())
            {
                return;
            }

            var DB = context.Database;

            if (isClearIds)
            {
                var tableName = context.Model.FindEntityType(typeof(T)).GetTableName();
                table.AddRange(data);

                using var transaction = DB.BeginTransaction();

                DB.ExecuteSqlRaw($"SET IDENTITY_INSERT [dbo].[{tableName}] ON");
                context.SaveChanges();
                DB.ExecuteSqlRaw($"SET IDENTITY_INSERT [dbo].[{tableName}] OFF");

                transaction.Commit();
            }
            else
            {
                data.ForEach(t => t.Id = 0);
                table.AddRange(data);

                using var transaction = DB.BeginTransaction();
                db.SaveChanges();
                transaction.Commit();
            }
        }
Example #9
0
        private void InitializeProducts()
        {
            if (_db.Products.Any())
            {
                _Logger.LogInformation("Добавление исходных данных в БД не требуется");
                return;
            }


            using (_db.Database.BeginTransaction())
            {
                _db.Categories.AddRange(TestData.Categories);

                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Categories] ON");
                _db.SaveChanges();
                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Categories] OFF");

                _db.Database.CommitTransaction();
            }

            _Logger.LogInformation("Добавление брендов...");
            using (_db.Database.BeginTransaction())
            {
                _db.Brands.AddRange(TestData.Brands);

                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Brands] ON");
                _db.SaveChanges();
                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Brands] OFF");

                _db.Database.CommitTransaction();
            }

            _Logger.LogInformation("Добавление товаров...");
            using (_db.Database.BeginTransaction())
            {
                _db.Products.AddRange(TestData.Products);

                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Products] ON");
                _db.SaveChanges();
                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Products] OFF");

                _db.Database.CommitTransaction();
            }
        }
Example #10
0
        private void InitializeProduct()
        {
            if (db.Products.Any())
            {
                logger.LogInformation("Добавление исходных данных в БД не требуется");
                return;
            }

            logger.LogInformation("Добавление секций...");

            using (db.Database.BeginTransaction())
            {
                db.Sections.AddRange(TestData.Sections);
                db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Sections] ON");
                db.SaveChanges();
                db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Sections] OFF");
                db.Database.CommitTransaction();
            }

            logger.LogInformation("Добавление брендов...");

            using (db.Database.BeginTransaction())
            {
                db.Brands.AddRange(TestData.Brands);
                db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Brands] ON");
                db.SaveChanges();
                db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Brands] OFF");
                db.Database.CommitTransaction();
            }

            logger.LogInformation("Добавление товаров...");

            using (db.Database.BeginTransaction())
            {
                db.Products.AddRange(TestData.Products);
                db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Products] ON");
                db.SaveChanges();
                db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Products] OFF");
                db.Database.CommitTransaction();
            }

            logger.LogInformation("Добавление исходных данных выполнено успешно");
        }
        private void InitializeProducts()
        {
            var db = _db.Database;

            if (_db.Products.Any())
            {
                return;
            }

            using (db.BeginTransaction())
            {
                _db.Sections.AddRange(TestData.Sections);

                db.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[ProductSection] ON");
                _db.SaveChanges();
                db.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[ProductSection] OFF");

                db.CommitTransaction();
            }

            using (var transaction = db.BeginTransaction())
            {
                _db.Brands.AddRange(TestData.Brands);

                db.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[ProductBrand] ON");
                _db.SaveChanges();
                db.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[ProductBrand] OFF");

                transaction.Commit();
            }

            using (var transaction = db.BeginTransaction())
            {
                _db.Products.AddRange(TestData.Products);


                db.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Products] ON");
                _db.SaveChanges();
                db.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Products] OFF");

                transaction.Commit();
            }
        }
Example #12
0
        private void InitializeProducts()
        {
            if (_webStoreDB.Products.Any())
            {
                return;
            }

            using (_webStoreDB.Database.BeginTransaction())
            {
                _webStoreDB.Sections.AddRange(TestData.Sections);

                _webStoreDB.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Sections] ON");
                _webStoreDB.SaveChanges();
                _webStoreDB.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Sections] OFF");


                _webStoreDB.Database.CommitTransaction();
            }

            using (_webStoreDB.Database.BeginTransaction())
            {
                _webStoreDB.Brands.AddRange(TestData.Brands);

                _webStoreDB.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Brands] ON");
                _webStoreDB.SaveChanges();
                _webStoreDB.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Brands] OFF");


                _webStoreDB.Database.CommitTransaction();
            }

            using (_webStoreDB.Database.BeginTransaction())
            {
                _webStoreDB.Products.AddRange(TestData.Products);

                _webStoreDB.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Products] ON");
                _webStoreDB.SaveChanges();
                _webStoreDB.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Products] OFF");


                _webStoreDB.Database.CommitTransaction();
            }
        }
Example #13
0
        private void InitializeEmployee()
        {
            var db = _db.Database;

            if (_db.Employees.Any())
            {
                return;
            }

            using (db.BeginTransaction())
            {
                var employees = TestData.Employees.ToList();
                employees.ForEach(e => e.Id = 0);
                _db.Employees.AddRange(employees);

                _db.SaveChanges();
                db.CommitTransaction();
            }
        }
Example #14
0
        private void InitializeProducts()
        {
            var db = _db.Database;

            if (_db.Products.Any())
            {
                return;                     //если в бд есть хоть 1 товар
            }
            using (db.BeginTransaction())
            {
                _db.Sections.AddRange(TestData.Sections);                          //добавление секций в контекст

                db.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[ProductSection] ON"); //переключение таблицы в ручной режим
                _db.SaveChanges();
                db.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[ProductSection] OFF");

                db.CommitTransaction();
            }

            using (var transaction = db.BeginTransaction())
            {
                _db.Brands.AddRange(TestData.Brands);

                db.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[ProductBrand] ON");
                _db.SaveChanges();
                db.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[ProductBrand] OFF");

                transaction.Commit();
            }

            using (var transaction = db.BeginTransaction())
            {
                _db.Products.AddRange(TestData.Products);


                db.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Products] ON");
                _db.SaveChanges();
                db.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Products] OFF");

                transaction.Commit();
            }
        }
Example #15
0
 public void SaveChanges()
 {
     try
     {
         db.SaveChanges();
     }
     catch (Exception ex)
     {
         throw new Exception($"Something bad happened while committing changes/n/n{ex.Message}");
     }
 }
Example #16
0
        public void InitializeProducts()
        {
            if (_db.Products.Any())
            {
                return;
            }

            using (_db.Database.BeginTransaction())
            {
                _db.Sections.AddRange(_inMemoryDb.Sections);

                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Sections] ON");
                _db.SaveChanges();
                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Sections] OFF");

                _db.Database.CommitTransaction();
            }

            using (_db.Database.BeginTransaction())
            {
                _db.Brands.AddRange(_inMemoryDb.Brands);

                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Brands] ON");
                _db.SaveChanges();
                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Brands] OFF");

                _db.Database.CommitTransaction();
            }

            using (_db.Database.BeginTransaction())
            {
                _db.Products.AddRange(_inMemoryDb.Products);

                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Products] ON");
                _db.SaveChanges();
                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Products] OFF");

                _db.Database.CommitTransaction();
            }
        }
Example #17
0
        private void InitialiseProducts()
        {
            var db = _db.Database;

            //если есть хоть один товар, то таблица считается проинициализированной
            if (_db.Products.Any())
            {
                return;
            }

            //добавляем бд транзакциями: если будет ошибка, всё откатится назад
            using (db.BeginTransaction())
            {
                _db.AddRange(TestData.Sections);
                db.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[ProductSection] ON");
                _db.SaveChanges();
                db.ExecuteSqlRaw("SET IDENTITY_INSERT  [dbo].[ProductSection] OFF");

                db.CommitTransaction();
            }

            using (var transaction = db.BeginTransaction())
            {
                _db.AddRange(TestData.Brands);
                db.ExecuteSqlRaw("SET IDENTITY_INSERT  [dbo].[ProductBrand] ON");
                _db.SaveChanges();
                db.ExecuteSqlRaw("SET IDENTITY_INSERT  [dbo].[ProductBrand] OFF");
                transaction.Commit();
            }

            using (db.BeginTransaction())
            {
                _db.AddRange(TestData.Products);
                db.ExecuteSqlRaw("SET IDENTITY_INSERT  [dbo].[Products] ON");
                _db.SaveChanges();
                db.ExecuteSqlRaw("SET IDENTITY_INSERT  [dbo].[Products] OFF");
                db.CommitTransaction();
            }
        }
        private void InitializeProducts()
        {
            if (_db.Products.Any())
            {
                _Logger.LogInformation("Инициализация товаров не нужна.");
                return;
            }

            _Logger.LogInformation("Инициализация секций...");

            var products_sections = TestData.Sections.Join(
                TestData.Products,
                section => section.Id,
                product => product.SectionId,
                (section, product) => (section, product));

            foreach (var(section, product) in products_sections)
            {
                section.Products.Add(product);
            }

            var products_brands = TestData.Brands.Join(
                TestData.Products,
                brand => brand.Id,
                product => product.BrandId,
                (brand, product) => (brand, product));

            foreach (var(brand, product) in products_brands)
            {
                brand.Products.Add(product);
            }

            var section_section = TestData.Sections.Join(
                TestData.Sections,
                parent => parent.Id,
                child => child.ParentId,
                (parent, child) => (parent, child));

            foreach (var(parent, child) in section_section)
            {
                child.Parent = parent;
            }

            foreach (var product in TestData.Products)
            {
                product.Id        = 0;
                product.BrandId   = null;
                product.SectionId = 0;
            }

            foreach (var brand in TestData.Brands)
            {
                brand.Id = 0;
            }

            foreach (var section in TestData.Sections)
            {
                section.Id       = 0;
                section.ParentId = null;
            }

            using (_db.Database.BeginTransaction())
            {
                _db.Products.AddRange(TestData.Products);
                _db.Sections.AddRange(TestData.Sections);
                _db.Brands.AddRange(TestData.Brands);

                _db.SaveChanges();
                _db.Database.CommitTransaction();
            }

            _Logger.LogInformation("Инициализация товаров завершена.");
        }
        private void InitializeProducts()
        {
            if (_db.Products.Any()) // если в контексте есть хотя бы один товар
            {
                _Logger.LogInformation("Каталог товаров уже инециализирован");
                return; // это значит, что БД уже проинициализирована и дальнейшая работа инициализатора не требуется
            }


            var db = _db.Database;

            // если товаров нет, то заполняем БД сперва секциями, потом брендами, потом товарами

            using (db.BeginTransaction())                                           // с помощью транзакций - можем добавить либо все секции вместе, либо не добавлять ни одной.
            {                                                                       //Если хотя бы одна секция не сможет быть добавлена, значит вся операция откатится обратно
                _db.Sections.AddRange(TestData.Sections);                           // добавляем все секции

                db.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[ProductSections] ON"); // отключаем первичный ключ (БД не любит жестко заданный)

                _db.SaveChanges();

                db.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[ProductSections] OFF");

                db.CommitTransaction();
            }

            using (db.BeginTransaction())
            {
                _db.Brands.AddRange(TestData.Brands);

                db.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[ProductBrands] ON");

                _db.SaveChanges();

                db.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[ProductBrands] OFF");

                db.CommitTransaction();
            }

            using (db.BeginTransaction())
            {
                _db.Products.AddRange(TestData.Products);

                db.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Products] ON");

                _db.SaveChanges();

                db.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Products] OFF");

                db.CommitTransaction();
            }



            /*
             * var products = TestData.Products;
             * var sections = TestData.Sections;
             * var brands = TestData.Brands;
             *
             * var product_section = products.Join(   // указываем,что хотим объединиться по двум ключам: у товара внешний ключ-SectionId, а у секции первичный ключ-Id
             *  sections,
             *  p => p.SectionId,
             *  s => s.Id, (product, section) => (product, section));
             *
             * foreach(var (product, section) in product_section)
             * {
             *  product.Section = section;
             *  product.SectionId = 0;    // сбрасываем внешний ключ
             * }
             *
             * var product_brand = products.Join(
             * brands,
             * p => p.BrandId,
             * b => b.Id, (product, brand) => (product, brand));
             *
             * foreach (var (product, brand) in product_brand)
             * {
             *  product.Brand = brand;
             *  product.BrandId = null;
             * }
             *
             * foreach (var product in products)
             *  product.Id = 0;
             *
             * var child_section = sections.Join(sections,
             *  child => child.ParentId,
             *  parent => parent.Id,
             *  (child, parent) => (child, parent));
             *
             * foreach(var(child, parent) in child_section)
             * {
             *  child.ParentSection = parent;
             *  child.ParentId = null;
             * }
             *
             * foreach (var section in sections)
             *  section.Id = 0;
             *
             * foreach (var brand in brands)
             *  brand.Id = 0;
             *
             * using (db.BeginTransaction())
             * {
             *  _db.Sections.AddRange(sections);
             *  _db.Brands.AddRange(brands);
             *  _db.Products.AddRange(products);
             *  _db.SaveChanges();
             *  db.CommitTransaction();
             * }
             */
        }
Example #20
0
 public void SaveChanges() => _db.SaveChanges();
        private void InitializeProducts()
        {
            var timer = Stopwatch.StartNew();

            if (_db.Products.Any())
            {
                _Logger.LogInformation("Инициализация  БД  товарами не требуется  ({0:0.0###} с)", timer.Elapsed.TotalSeconds);
                return;
            }

            _Logger.LogInformation("Инициализация товаров .... ({0:0.0###} с)", timer.Elapsed.TotalSeconds);

            _Logger.LogInformation("Добавляем Sections .... ({0:0.0###} с)", timer.Elapsed.TotalSeconds);

            using (_db.Database.BeginTransaction())
            {
                _db.Sections.AddRange(TestData.Sections);

                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Sections] ON");

                _db.SaveChanges();

                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Sections] OFF");

                _db.Database.CommitTransaction();
            }

            _Logger.LogInformation("Sections успешно добавлены ({0:0.0###} с)", timer.Elapsed.TotalSeconds);

            _Logger.LogInformation("Добавляем Brands.... ({0:0.0###} с)", timer.Elapsed.TotalSeconds);

            using (_db.Database.BeginTransaction())
            {
                _db.Brands.AddRange(TestData.Brands);

                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Brands] ON");

                _db.SaveChanges();

                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Brands] OFF");

                _db.Database.CommitTransaction();
            }

            _Logger.LogInformation("Brands успешно добавлены  ({0:0.0###} с)", timer.Elapsed.TotalSeconds);

            _Logger.LogInformation("Добавляем Products.... ({0:0.0###} с)", timer.Elapsed.TotalSeconds);

            using (_db.Database.BeginTransaction())
            {
                _db.Products.AddRange(TestData.Products);

                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Products] ON");

                _db.SaveChanges();

                _db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Products] OFF");

                _db.Database.CommitTransaction();
            }

            _Logger.LogInformation("Products успешно добавлены  ({0:0.0###} с)", timer.Elapsed.TotalSeconds);

            _Logger.LogInformation("Инициализация товаров выполнено успешно ({0:0.0###} с)", timer.Elapsed.TotalSeconds);
        }
Example #22
0
 public void SaveChanges()
 {
     dB.SaveChanges();
 }
Example #23
0
        private void InitializeProducts()
        {
            if (_db.Products.Any())
            {
                return;
            }

            var db = _db.Database;

            using (db.BeginTransaction())
            {
                _db.Sections.AddRange(TestData.Sections);

                db.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[ProductSections] ON");
                _db.SaveChanges();
                db.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[ProductSections] OFF");

                db.CommitTransaction();
            }

            using (db.BeginTransaction())
            {
                _db.Brands.AddRange(TestData.Brands);

                db.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[ProductBrands] ON");
                _db.SaveChanges();
                db.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[ProductBrands] OFF");

                db.CommitTransaction();
            }

            using (db.BeginTransaction())
            {
                _db.Products.AddRange(TestData.Products);

                db.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Products] ON");
                _db.SaveChanges();
                db.ExecuteSqlRaw("SET IDENTITY_INSERT [dbo].[Products] OFF");

                db.CommitTransaction();
            }

            //var products = TestData.Products;
            //var sections = TestData.Sections;
            //var brands = TestData.Brands;

            //var product_section = products.Join(
            //    sections,
            //    p => p.SectionId,
            //    s => s.Id,
            //    (product, section) => (product, section));

            //foreach (var (product, section) in product_section)
            //{
            //    product.Section = section;
            //    product.SectionId = 0;
            //}

            //var product_brand = products.Join(
            //    brands,
            //    p => p.BrandId,
            //    b => b.Id,
            //    (product, brand) => (product, brand));

            //foreach (var (product, brand) in product_brand)
            //{
            //    product.Brand = brand;
            //    product.BrandId = null;
            //}

            //foreach (var product in products)
            //    product.Id = 0;

            //var child_sections = sections.Join(
            //    sections,
            //    child => child.ParentId,
            //    parent => parent.Id,
            //    (child, parent) => (child, parent));

            //foreach (var (child, parent) in child_sections)
            //{
            //    child.ParentSection = parent;
            //    child.ParentId = null;
            //}

            //foreach (var section in sections)
            //    section.Id = 0;

            //foreach (var brand in brands)
            //    brand.Id = 0;


            //using (db.BeginTransaction())
            //{
            //    _db.Sections.AddRange(sections);
            //    _db.Brands.AddRange(brands);
            //    _db.Products.AddRange(products);
            //    _db.SaveChanges();
            //    db.CommitTransaction();
            //}
        }
Example #24
0
        private void InitializeProducts()
        {
            var timer = Stopwatch.StartNew();

            if (_db.Products.Any())
            {
                _Logger.LogInformation("Инициализация БД товарами не требуется");
                return;
            }

            _Logger.LogInformation("Инициализация товаров...");

            var products_sctions = TestData.Sections.Join(
                TestData.Products,
                s => s.Id,
                p => p.SectionId,
                (section, product) => (section, product));

            foreach (var(section, product) in products_sctions)
            {
                section.Products.Add(product);
            }

            var products_brands = TestData.Brands.Join(
                TestData.Products,
                b => b.Id,
                p => p.BrandId,
                (brand, product) => (brand, product));

            foreach (var(brand, product) in products_brands)
            {
                brand.Products.Add(product);
            }

            var section_section = TestData.Sections.Join(
                TestData.Sections,
                parent_section => parent_section.Id,
                child_section => child_section.ParentId,
                (parent, child) => (parent, child));

            foreach (var(parent, child) in section_section)
            {
                child.Parent = parent;
            }

            foreach (var product in TestData.Products)
            {
                product.Id        = 0;
                product.SectionId = 0;
                product.BrandId   = null;
            }

            foreach (var section in TestData.Sections)
            {
                section.Id       = 0;
                section.ParentId = null;
            }

            foreach (var brand in TestData.Brands)
            {
                brand.Id = 0;
            }

            using (_db.Database.BeginTransaction())
            {
                _db.Products.AddRange(TestData.Products);
                _db.Sections.AddRange(TestData.Sections);
                _db.Brands.AddRange(TestData.Brands);

                _db.SaveChanges();
                _db.Database.CommitTransaction();
            }

            _Logger.LogInformation("Инициализация товаров выполнена успешно ({0:0.0###})",
                                   timer.Elapsed.TotalSeconds);
        }
Example #25
0
 public void SaveChanges()
 {
     _webStoreDb.SaveChanges();
 }
Example #26
0
 public void SaveChanges()
 {
     _db.SaveChanges();
 }
Example #27
0
 public void AddProduct(Product product)
 {
     db.Products.Update(product);
     db.SaveChanges();
 }