public async Task Update(int id, CategoriaCreateOrUpdateDto model)
        {
            var entry = await _context.Categoria.Include(x => x.ProductoCategorias).SingleAsync(x => x.IdCategoria == id);

            entry.Nombre      = model.Nombre;
            entry.Descripcion = model.Descripcion;
            //Tenemos que actualizar todos los productos que estan relacionados con la categoria, para eso:
            //Primero analizamos los nuevos productos:
            var antiguos = entry.ProductoCategorias.Select(x => x.IdProducto);
            var nuevos   = model.IdProductos.Except(antiguos);

            foreach (var item in nuevos)
            {
                await _context.ProductoCategoria.AddAsync(new Model.Productos.ProductoCategoria
                {
                    IdCategoria = entry.IdCategoria,
                    IdProducto  = item,
                });
            }
            var eliminar = antiguos.Except(nuevos);

            foreach (var item in eliminar)
            {
                _context.ProductoCategoria.Remove(entry.ProductoCategorias.Find(x => x.IdProductoCategoria == item));
            }
            await _context.SaveChangesAsync();
        }
        public async Task Create(CategoriaCreateOrUpdateDto model)
        {
            var entry = new Model.Productos.Categoria
            {
                Nombre      = model.Nombre,
                Descripcion = model.Descripcion,
            };
            await _context.Categoria.AddAsync(entry);

            await _context.SaveChangesAsync();

            //Ahora creamos las relaciones con los productos:
            foreach (var item in model.IdProductos)
            {
                await _context.ProductoCategoria.AddAsync(new Model.Productos.ProductoCategoria
                {
                    IdCategoria = entry.IdCategoria,
                    IdProducto  = item
                });
            }
            await _context.SaveChangesAsync();
        }
예제 #3
0
        public async Task <ActionResult> Update(int id, CategoriaCreateOrUpdateDto model)
        {
            await _service.Update(id, model);

            return(Ok());
        }
예제 #4
0
        public async Task <ActionResult> Create(CategoriaCreateOrUpdateDto model)
        {
            await _service.Create(model);

            return(Ok());
        }