示例#1
0
 public ActionResult NovoAutor(NovoLivroAutorViewModel vm)
 {
     try
     {
         var md    = db.Livros.Include(x => x.Editora).Include(x => x.Autores).FirstOrDefault(x => x.LivroId == vm.LivroId);
         var novos = vm.Autores.Where(x => x.Selected);
         var qtde  = 0;
         foreach (var novo in novos)
         {
             if (md.Autores.Count(x => x.AutorId == novo.AutorId) == 0)
             {
                 var novoAutor = db.Autores.FirstOrDefault(x => x.AutorId == novo.AutorId);
                 if (novoAutor != null)
                 {
                     md.Autores.Add(novoAutor);
                     qtde++;
                 }
             }
         }
         if (qtde > 0)
         {
             db.SaveChanges();
         }
         return(RedirectToAction("Alterar", new { id = vm.LivroId }));
     }
     catch { }
     return(RedirectToAction("Index"));
 }
示例#2
0
        public ActionResult NovoAutor(int livroId)
        {
            try
            {
                var livro = db.Livros.Include(x => x.Autores).FirstOrDefault(x => x.LivroId == livroId);
                if (livro != null)
                {
                    List <Autor> autores = null;
                    if (livro.Autores != null)
                    {
                        var ids = livro.Autores.Select(x => x.AutorId).ToArray();
                        autores = db.Autores.Where(x => !ids.Contains(x.AutorId)).ToList();
                    }
                    else
                    {
                        autores = db.Autores.ToList();
                    }

                    var vm = new NovoLivroAutorViewModel(livroId, livro.Titulo);

                    if (autores != null)
                    {
                        autores.ForEach(x => vm.Autores.Add(new AutorCheckBox(x.AutorId, x.Nome)));
                    }

                    return(View(vm));
                }
            }
            catch { }
            return(RedirectToAction("Index"));
        }