private static async Task <Dictionary <int, Product> > GetSubchapterProductsFromDbAsync(int subchapterId) { Dictionary <int, Product> productsFromDb; using (var db = new DbContext()) { var request = db.Products.AsNoTracking().Where(x => x.SubchapterId == subchapterId) .Include(x => x.Creator) .Include(x => x.Organizer) .Include(x => x.Prefix) .Include(x => x.Chapter) .Include(x => x.Subсhapter); productsFromDb = await request.ToDictionaryAsync(p => p.Id).ConfigureAwait(false); foreach (var product in productsFromDb.Values) { if (Db.Tags.ProductsAndTags.ContainsKey(product.Id)) { product.Tags = Db.Tags.ProductsAndTags[product.Id]; } } } return(productsFromDb); }
private async void AddProductFromUrl() { var category = SelectedCategory; var dialog = new AddProductFromUrlWindow(); if (dialog.ShowDialog() == true) { string url = dialog.Url; Product addedProduct = null; try { var addedProductId = Products.ParseId(url); if (category.Products.Any(p => p.Model.Id == addedProductId)) { await MessageBox.ShowAsync("Данная складчина уже была добавлена ранее.", "Информация", MessageBoxButton.OK, MessageBoxImage.Information).ConfigureAwait(false); return; } Product dbProduct; using (var context = new DbContext()) { dbProduct = await context.Products.AsNoTracking().Where(x => x.Id == addedProductId) .Include(p => p.Prefix) .Include(p => p.Chapter) .Include(p => p.Subсhapter) .Include(p => p.Creator) .Include(p => p.Organizer) .FirstOrDefaultAsync().ConfigureAwait(false); } if (dbProduct != null) { addedProduct = dbProduct; } else { var skApi = new SkladchikApiClient(new CancellationToken()); bool isNeedGetCookie = await Cookies.IsNeedGetCookie().ConfigureAwait(false); if (isNeedGetCookie) { var cookieContainer = Cookies.GetSkladchikCookie(); skApi.CookieContainer = cookieContainer; if (cookieContainer.Count == 0) { await MessageBox.ShowAsync("Добавление складчины невозможно. Загрузите сайт в браузере и попробуйте заново.", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error).ConfigureAwait(false); return; } } addedProduct = await skApi.Products.GetByUrlAsync(url).ConfigureAwait(false); } } catch (System.Exception) { // ignored } if (addedProduct == null) { await MessageBox.ShowAsync("Ошибка добавления. Проверьте указанный URL.", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error).ConfigureAwait(false); return; } ProductVM productVm; if (_allProducts.ContainsKey(addedProduct.Id)) { productVm = _allProducts[addedProduct.Id]; } else { productVm = new ProductVM(addedProduct); _allProducts.Add(addedProduct.Id, productVm); } await Db.Products.AddOrUpdateAsync(new List <Product> { addedProduct }).ConfigureAwait(false); await Db.Categories.AddProductsAsync(category.Model, new List <Product> { addedProduct }) .ConfigureAwait(false); await ProductManagerVM.AddProductToCategoryAsync(category, new List <ProductVM> { productVm }) .ConfigureAwait(false); } }