2
I want to register a person, which I have divided into three entities: Person, Contact and Address. And I want it to be just a registration form.
My create action in the person controller looks like this:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(PessoaViewModel pessoaViewModel)
{
if (ModelState.IsValid)
{
pessoaViewModel = _pessoaAppService.Adicionar(pessoaViewModel);
return RedirectToAction("Index");
}
return View(pessoaViewModel);
}
Add Method in Application Layer:
public PessoaViewModel Adicionar(PessoaViewModel pessoaViewModel)
{
var pessoa = Mapper.Map<PessoaViewModel, Pessoa>(pessoaViewModel);
BeginTransaction();
var pessoaValidacao = _pessoaService.Adicionar(pessoa);
pessoaViewModel = Mapper.Map<Pessoa, PessoaViewModel>(pessoaValidacao);
Commit();
return pessoaViewModel;
}
Add to Domain layer:
public Pessoa Adicionar(Pessoa pessoa)
{
return _pessoaRepositorio.Adicionar(pessoa);
}
Generic repository:
public virtual TEntity Adicionar(TEntity obj)
{
return DbSet.Add(obj);
}
And I have some partials views that make the form:
<!-- todo o formulario-->
<div class="panel-body">
<div class="tab-content">
<!-- primeira aba -->
<div id="tab-1" class="tab-pane active">
@Html.Partial("_DadosCadastrais")
</div>
<!-- segunda aba -->
<div id="tab-2" class="tab-pane">
@Html.Partial("_Contato")
</div>
<!-- terceira aba -->
<div id="tab-3" class="tab-pane">
@Html.Partial("_EnderecoPessoa")
</div>
</div>
and each partial view uses a different viewModel:
contact:
@model V1.Aplicacao.ViewModels.PessoaContatoViewModel
Addressee:
@model V1.Aplicacao.ViewModels.EnderecoViewModel
Person:
@model V1.Aplicacao.ViewModels.PessoaViewModel
How do I use the person create method to register these three entities in the bank?
You have 1 person object, and inside it you put the other 2 objects that you want to move from the view to the controller, then just register. From what I understand it can be done like this.
– PauloHDSousa
Personal Viewmodel can be composed of Personal Contactoviewmodel, Addressmodel and Personal Viewmodel. Use these Personal properties in the partitals.
– Rafael Companhoni
Yes I did, but then in my Personal classappservice, which converts viewModel to entity, how do I do? would be something like :
var endereco = Mapper.Map<PessoaViewModel, Endereco>(PessoaViewModel); Pessoa.Enderecos.Add(endereco);
Or you don’t have to do that?– Aesir
It will be necessary to declare the mapping rules of Peoplescontactoviewmodel, Addressmodel and Peoplesviewmodel before the rule of Peoplesviewmodel. So Automapper will know how to use them.
– Rafael Companhoni