public async Task <IActionResult> Create([Bind("Amigo,Jogos,DataPrevistaDevolucao,DataDevolucao")] CadastroEmprestimoViewModel emprestimoViewModel) { if (ModelState.IsValid) { var emprestimo = new Emprestimo { DataCadastro = DateTime.Now, DataPrevistaDevolucao = emprestimoViewModel.DataPrevistaDevolucao, Amigo = await UnitOfWork.GetRepositoryAsync <Amigo>() .SingleAsync(e => e.Id == emprestimoViewModel.Amigo), Emprestimos = new List <EmprestimoJogo>() }; foreach (var jogo in emprestimoViewModel.Jogos) { emprestimo.Emprestimos.Add(new EmprestimoJogo { DataCadastro = DateTime.Now, Emprestimo = emprestimo, Jogo = await UnitOfWork.GetRepositoryAsync <Jogo>().SingleAsync(e => e.Id == jogo) }); } emprestimo.DataCadastro = DateTime.Now; UnitOfWork.GetRepositoryAsync <Emprestimo>().UpdateAsync(emprestimo); UnitOfWork.SaveChanges(); return(RedirectToAction(nameof(Index))); } return(View(emprestimoViewModel)); }
private void InicializaViewData(CadastroEmprestimoViewModel emprestimo = null) { ViewData["Amigo"] = new SelectList(UnitOfWork.GetRepositoryAsync <Amigo>().GetAsync(e => !e.Excluido).OrderBy(e => e.Nome), "Id", "Nome", emprestimo?.Amigo); var jogos = UnitOfWork.GetRepositoryAsync <Jogo>() .GetAsync(e => !e.Excluido && e.Emprestimos.All(i => i.Emprestimo.DataDevolucao != null), include: i => i.Include(e => e.Emprestimos)).ToList(); if (emprestimo != null) { jogos.AddRange(emprestimo.Jogos.Select(emprestimoJogo => UnitOfWork.GetRepositoryAsync <Jogo>().SingleAsync(e => e.Id == emprestimoJogo).Result)); //jogos.AddRange(emprestimo.Jogos.Select(emprestimoJogo => await UnitOfWork.GetRepositoryAsync<Jogo>().Sin().FirstOrDefault(e => e.Id == emprestimoJogo))); } ViewData["Jogos"] = new MultiSelectList(jogos.OrderBy(e => e.NomeJogo), "Id", "NomeJogo", emprestimo?.Jogos); }