public int Add(ProductModel model) { var newProduct = model.Adapt <ProductEntity>(); if (model.BrandId.HasValue) { if (!brandRepository.FindById(model.BrandId.Value)) { throw new ValidatorException("Unkonwn brand"); } } if (model.Categories.Count > 0) { var categoryIds = model.Categories .Select(x => x.CategoryId) .ToList(); if (!categoryRepository.FindByIds(categoryIds)) { throw new ValidatorException("Unkonwn category"); } var newProductCategories = new List <ProductCategoryEntity>(); foreach (var category in model.Categories) { var newProductCategory = new ProductCategoryEntity { ProductId = newProduct.ProductId, Product = newProduct, CategoryId = category.CategoryId }; newProductCategories.Add(newProductCategory); } productCategoryRepository.AddCategories(newProductCategories); } productValidator.Validate(newProduct); productRepository.Add(newProduct); return(newProduct.ProductId); }