Ejemplo n.º 1
0
        public void UpdateProduct(Product product)
        {
            // help => http://www.entityframeworktutorial.net/EntityFramework4.3/update-many-to-many-entity-using-dbcontext.aspx
            // don't forget equals implementation for objects

            var existingProduct =
                _context.Products.Include("Categories").FirstOrDefault(p => p.Id == product.Id);

            if (existingProduct == null)
            {
                throw new ArgumentException("Product was not found");
            }

            var deleteCategories =
                existingProduct.Categories.Except(product.Categories).ToList();

            var addedCategories =
                product.Categories.Except(existingProduct.Categories).ToList();

            deleteCategories.ForEach(category => existingProduct.Categories.Remove(category));

            foreach (Category category in addedCategories)
            {
                _context.Categories.Attach(category);
                existingProduct.Categories.Add(category);
            }

            _context.SaveChanges();

            _context.DetachAllEntities();
            product.Categories.Clear();
            _context.Products.Attach(product);
            _context.Entry(product).State = EntityState.Modified;
            _context.SaveChanges();
        }