How to load references before performing Insert?

Asked

Viewed 31 times

0

I have a method that receives Id parameters. These are, referenced in a model, however, I need to be loaded your references before saved, because I need this information to communicate with a API external.

Code:

public void Salvar(int contaBancariaId, int clienteId, DateTime vencimento, decimal valor) 
{
    var conta = new ContaReceber();
    conta.ContaBancariaId = contaBancariaId;
    conta.ClienteId = clienteId;
    conta.Vencimento = vencimento;
    conta.Valor = valor;

    conta.Boleto =_api.CriarBoleto(conta.ContaBancaria.Agencia,conta.ContaBancaria.Conta, conta.Cliente.Nome,...);

    _dbContext.Contas.Add(conta);
    _dbContext.SaveChanges();
}

The Create Boleto method returns me the Boleto model so I can reference my account, using 1-0/1 mapping.

For this reason I need to access the properties of Cliente and ContaBancaria.

So much Cliente and ContaBancaria are properties virtual.

So far I have saved, loaded using Explicit Load and saving again:

    conta.Vencimento = vencimento;
    conta.Valor = valor;

    _dbContext.Contas.Add(conta);
    _dbContext.SaveChanges();

    _dbContext.Entry(conta).Reference(x => x.Cliente).Load();
    _dbContext.Entry(conta).Reference(x => x.ContaBancaria).Load();

    conta.Boleto =_api.CriarBoleto(conta.ContaBancaria.Agencia,conta.ContaBancaria.Conta, conta.Cliente.Nome,...);

   _dbContext.SaveChanges();

This does not seem to be the best way. Suggestions?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.